get_messages on handshake, send set_variables only to other users

This commit is contained in:
arne 2023-01-29 21:28:47 +01:00
parent a1106c4b22
commit efc8f565bf
2 changed files with 28 additions and 12 deletions

View File

@ -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) {

38
test.py
View File

@ -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)