infa735-drawbridge/examples/server.py

48 lines
1.2 KiB
Python
Raw Permalink Normal View History

2023-12-04 14:09:05 -08:00
#!/usr/bin/env python
import asyncio
import websockets
import json
connected = set()
def sanitize(message):
# A very secure sanitization function.
return message.replace('<', '').replace('>', '')
async def handler(websocket):
try:
connected.add(websocket)
print(f"Connected: {websocket.remote_address[0]}")
while True:
try:
message = await websocket.recv()
sanitized_message = sanitize(message)
sanitized_sender = sanitize(websocket.remote_address[0])
payload = json.dumps({
'sender': sanitized_sender,
'message': sanitized_message
})
print(f"{websocket.remote_address[0]} says: {message}")
for conn in connected:
await conn.send(payload)
except Exception:
break
finally:
print(f"Disconnected: {websocket.remote_address[0]}.")
connected.remove(websocket)
async def main():
async with websockets.serve(handler, "", 80, compression=None):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())