From efc8f565bfbde89497107ff1405a3951d464b461 Mon Sep 17 00:00:00 2001 From: arne Date: Sun, 29 Jan 2023 21:28:47 +0100 Subject: [PATCH] get_messages on handshake, send set_variables only to other users --- docs/client.html | 2 +- test.py | 38 +++++++++++++++++++++++++++----------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/docs/client.html b/docs/client.html index d267e89..94b18d9 100644 --- a/docs/client.html +++ b/docs/client.html @@ -25,7 +25,7 @@ user: "testClient"+Math.random() })); - setInterval(function() { setVariable('test','einTollerText'+Math.random()) }, 1000); + setInterval(function() { setVariable('test','einTollerText'+Math.random()) }, 5000); }; socket.onmessage = function(event) { diff --git a/test.py b/test.py index f31e4ae..1ab7e6d 100644 --- a/test.py +++ b/test.py @@ -3,6 +3,7 @@ import websockets import json clients = {} +vars = {} async def handshake(ws,j): if not clients.get(j.get('project_id')): @@ -11,10 +12,23 @@ async def handshake(ws,j): 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 get_variables(websocket,project_id,user): + for name,value in vars.get(project_id,{}).items(): + if not name: + continue + await websocket.send(json.dumps({"method":"set","name":name,"value":value})) + +async def set_variable(project_id,user,var): + if not vars.get(project_id,''): + vars[project_id] = {} + vars[project_id][var.get('name','')] = var.get('value','') + + data = json.dumps(var) + for name,ws in clients.get(project_id,{}).items(): + if name == user: + continue + print(f"> {name} - {data}") + await ws.send(data) async def disconnect(project_id,user): print("disconnecting",user) @@ -24,14 +38,16 @@ async def disconnect(project_id,user): async def process(websocket, path): project_id = "" user = "" - async for data in websocket: - print(f"< {user} - {data}") + async for msg in websocket: + print(f"< {user} - {msg}") 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) + data = json.loads(msg) + method = data.get('method','') + if method == 'handshake': + project_id,user = await handshake(websocket,data) + await get_variables(websocket,project_id,user) + if method in ['set','create']: + await set_variable(project_id,user,data) finally: pass await disconnect(project_id,user)