-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
36 lines (30 loc) · 1.12 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
#simple websockets brocaster
import asyncio
import websockets
clients = [] #to store all connected cleints
#handler for socket message activities
async def handler(websocket, path):
#print(path) #path is not used currently
if websocket not in clients:
clients.append(websocket) #append new cleint to the array
async for message in websocket:
print(message,'received from client') #print to console
await brocast(message) #send message to all clents
async def brocast(msg):
print(msg,' brocasting') #print to console
#iterate the clients
for websock in clients:
try:
await websock.send(msg) #send message to each client
except websockets.exceptions.ConnectionClosed:
#remove the client when it disconnects
print("Client disconnected. Do cleanup")
clients.remove(websock)
#pass
#starts the service and run forever
loop = asyncio.new_event_loop() #get an event loop
asyncio.set_event_loop(loop) #set the event loop to asyncio
loop.run_until_complete(
websockets.serve(handler, '192.168.0.140', 4545) #setup the websocket service and handler
) #hook to localhost:4545
loop.run_forever() #keep it running