Updated server
All checks were successful
Build and Push Multi-Platform Docker Image / build-and-push (push) Successful in 16s
All checks were successful
Build and Push Multi-Platform Docker Image / build-and-push (push) Successful in 16s
This commit is contained in:
27
server.py
27
server.py
@@ -18,6 +18,8 @@ CLIENT_LABELS_TS: dict[str, float] = {}
|
||||
# After this many seconds without an update, we'll clear their list
|
||||
STALE_TIMEOUT = 5.0
|
||||
|
||||
broadcast = False
|
||||
|
||||
async def handler(ws: websockets.WebSocketServerProtocol):
|
||||
peer_id = None
|
||||
try:
|
||||
@@ -50,9 +52,21 @@ async def handler(ws: websockets.WebSocketServerProtocol):
|
||||
logging.info(f"Got labels from {peer_id}: {msg['labels']}")
|
||||
labels = msg.get("labels")
|
||||
if peer_id and isinstance(labels, list):
|
||||
CLIENT_LABELS[peer_id] = labels
|
||||
CLIENT_LABELS_TS[peer_id] = time.monotonic()
|
||||
logging.debug("Updated labels for %s: %s", peer_id, labels)
|
||||
|
||||
payload = json.dumps({
|
||||
"type": "broadcast_labels",
|
||||
"from": peer_id,
|
||||
"labels": labels
|
||||
})
|
||||
|
||||
# send to all except the originator
|
||||
count = 0
|
||||
for other_id, other_ws in CLIENTS.items():
|
||||
if other_id != peer_id:
|
||||
await other_ws.send(payload)
|
||||
count += 1
|
||||
|
||||
logging.info(f"Re-broadcasted labels to {count} other clients (excluding {peer_id})")
|
||||
else:
|
||||
logging.warning("Malformed labels payload from %s: %s", peer_id, raw)
|
||||
|
||||
@@ -102,14 +116,17 @@ async def broadcast_labels_periodically():
|
||||
|
||||
async def main():
|
||||
# start the broadcaster task
|
||||
broadcaster = asyncio.create_task(broadcast_labels_periodically())
|
||||
broadcaster = None
|
||||
if broadcast:
|
||||
broadcaster = asyncio.create_task(broadcast_labels_periodically())
|
||||
|
||||
# start the websocket server
|
||||
async with websockets.serve(handler, "0.0.0.0", 8080):
|
||||
logging.info("Signalling server listening on :8080")
|
||||
await asyncio.Future() # run forever
|
||||
|
||||
broadcaster.cancel()
|
||||
if broadcast:
|
||||
broadcaster.cancel()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user