-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
58 lines (40 loc) · 1.24 KB
/
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
import asyncio
import threading
import time
import signal
import sys
import websockets
clients = set()
async def handleClient(websocket, path):
clients.add(websocket)
try:
while True:
message = await websocket.recv()
# print("< {}".format(message))
await broadcastMessage(websocket, message)
# print("sent {}".format(message))
finally:
clients.remove(websocket)
async def broadcastMessage(origin, message):
destinations = clients - {origin}
messagesSent = 0
for dest in destinations:
await dest.send(message)
messagesSent = messagesSent + 1
# print("Sent message {} times: {}".format(messagesSent, message))
def websocketServer():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
start_server = websockets.serve(handleClient, '0.0.0.0', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
thread = threading.Thread(target=websocketServer, args=())
thread.daemon = True
thread.start()
def signal_handler(signal, frame):
print("\nStopping server.")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
while True:
time.sleep(20)