2024-08-27 19:44:15 +00:00
|
|
|
import asyncio
|
|
|
|
import websockets
|
|
|
|
import hashlib
|
|
|
|
|
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
|
|
|
|
connected_clients = set()
|
|
|
|
|
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 19:44:15 +00:00
|
|
|
connected_clients.add(websocket)
|
|
|
|
try:
|
|
|
|
async for message in websocket:
|
|
|
|
# Forward the message to all connected clients
|
|
|
|
for client in connected_clients:
|
|
|
|
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
|
|
|
|
connected_clients.remove(websocket)
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
# Start the WebSocket server
|
2024-08-27 20:26:35 +00:00
|
|
|
server = await websockets.asyncio.server.serve(handler, "localhost", 9999)
|
2024-08-27 19:44:15 +00:00
|
|
|
print("WebSocket server listening on ws://localhost:9999")
|
|
|
|
await server.wait_closed()
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
asyncio.run(main())
|