37 lines
621 B
Python
37 lines
621 B
Python
import json
|
|
import threading
|
|
|
|
_conns: set = set()
|
|
_lock = threading.Lock()
|
|
|
|
|
|
def register(ws) -> None:
|
|
with _lock:
|
|
_conns.add(ws)
|
|
|
|
|
|
def unregister(ws) -> None:
|
|
with _lock:
|
|
_conns.discard(ws)
|
|
|
|
|
|
def connected_count() -> int:
|
|
with _lock:
|
|
return len(_conns)
|
|
|
|
|
|
def push(msg: dict) -> None:
|
|
data = json.dumps(msg)
|
|
with _lock:
|
|
targets = list(_conns)
|
|
dead = []
|
|
for ws in targets:
|
|
try:
|
|
ws.send(data)
|
|
except Exception:
|
|
dead.append(ws)
|
|
if dead:
|
|
with _lock:
|
|
for ws in dead:
|
|
_conns.discard(ws)
|