2024-08-27 22:58:17 +00:00
|
|
|
#!/usr/bin/env python3
|
2024-08-27 19:44:15 +00:00
|
|
|
import asyncio
|
|
|
|
import websockets
|
|
|
|
import hashlib
|
2024-08-27 22:58:17 +00:00
|
|
|
import os
|
2024-08-27 19:44:15 +00:00
|
|
|
|
2024-08-27 20:26:35 +00:00
|
|
|
import websockets.asyncio.server
|
|
|
|
|
2024-08-27 19:44:15 +00:00
|
|
|
# List to store connected clients
|
2024-08-27 22:58:17 +00:00
|
|
|
connected_clients: dict[str, set] = dict()
|
2024-08-27 19:44:15 +00:00
|
|
|
|
2024-08-27 20:26:35 +00:00
|
|
|
async def handler(websocket):
|
2024-08-27 19:44:15 +00:00
|
|
|
# Register the new client
|
|
|
|
print(f"New client connected: {websocket}")
|
2024-08-27 20:26:35 +00:00
|
|
|
print(f"WRP: {websocket.request.path}")
|
2024-08-27 22:58:17 +00:00
|
|
|
if websocket.request.path not in connected_clients:
|
|
|
|
connected_clients[websocket.request.path] = set()
|
|
|
|
connected_clients[websocket.request.path].add(websocket)
|
|
|
|
|
2024-08-27 19:44:15 +00:00
|
|
|
try:
|
|
|
|
async for message in websocket:
|
2024-08-27 22:58:17 +00:00
|
|
|
# Forward the message to all connected clients on the same path
|
|
|
|
for client in connected_clients[websocket.request.path]:
|
2024-08-27 19:44:15 +00:00
|
|
|
if client != websocket:
|
|
|
|
print(f"WS>WS: ", hashlib.md5(message).hexdigest())
|
|
|
|
await client.send(message)
|
|
|
|
|
|
|
|
except websockets.exceptions.ConnectionClosed as e:
|
|
|
|
print(f"Connection closed: {e}")
|
|
|
|
finally:
|
|
|
|
# Unregister the client
|
2024-09-02 10:07:33 +00:00
|
|
|
connected_clients.get(websocket.request.path, set()).remove(websocket)
|
2024-08-27 19:44:15 +00:00
|
|
|
|
|
|
|
async def main():
|
|
|
|
# Start the WebSocket server
|
2024-08-27 22:58:17 +00:00
|
|
|
ws_port = os.environ.get("WS_PORT", 9999)
|
2024-09-02 09:41:22 +00:00
|
|
|
server = await websockets.asyncio.server.serve(handler, "", ws_port)
|
2024-08-27 22:58:17 +00:00
|
|
|
print(f"WebSocket server listening on ws://[::]:{ws_port}")
|
2024-08-27 19:44:15 +00:00
|
|
|
await server.wait_closed()
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
asyncio.run(main())
|