-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.py
28 lines (23 loc) · 855 Bytes
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import asyncio
import websockets
from dotenv import load_dotenv
import os
load_dotenv()
connected_clients = set()
async def echo(websocket, path):
# Add the client to the set of connected clients
connected_clients.add(websocket)
try:
async for message in websocket:
# Echo the message to all connected clients
for client in connected_clients:
await client.send(message)
finally:
# Remove the client from the set of connected clients when the connection is closed
connected_clients.remove(websocket)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
start_server = websockets.serve(echo, "localhost", os.getenv("WEBSOCKET_PORT"))
print('Server started at ws://localhost:' + os.getenv("WEBSOCKET_PORT"))
loop.run_until_complete(start_server)
loop.run_forever()