41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
import asyncio
|
|
import websockets
|
|
import json
|
|
|
|
clients = {}
|
|
|
|
async def handshake(ws,j):
|
|
if not clients.get(j.get('project_id')):
|
|
clients[j.get('project_id')] = {}
|
|
clients[j.get('project_id')][j.get('user')] = ws
|
|
print(f"{j.get('user')} connected from {ws.host}:{ws.port}")
|
|
return(j.get('project_id'),j.get('user'))
|
|
|
|
async def set_variable(j):
|
|
for name,ws in clients.get(j.get('project_id'),{}).items():
|
|
print(f"> {name} - {json.dumps(j)}")
|
|
await ws.send(json.dumps(j))
|
|
|
|
async def disconnect(project_id,user):
|
|
print("disconnecting",user)
|
|
clients.get(project_id,[]).pop(user)
|
|
|
|
|
|
async def process(websocket, path):
|
|
project_id = ""
|
|
user = ""
|
|
async for data in websocket:
|
|
print(f"< {user} - {data}")
|
|
try:
|
|
j = json.loads(data)
|
|
if j.get('method','') == 'handshake':
|
|
project_id,user = await handshake(websocket,j)
|
|
if j.get('method','') == 'set':
|
|
await set_variable(j)
|
|
finally:
|
|
pass
|
|
await disconnect(project_id,user)
|
|
|
|
start_server = websockets.serve(process, 'localhost', 5000, compression=None)
|
|
asyncio.get_event_loop().run_until_complete(start_server)
|
|
asyncio.get_event_loop().run_forever() |