The server keeps the most recent snapshot in memory (under the same lock as the client list). When a client connects it receives that snapshot right away, then continues to receive live updates on each collection cycle. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
import json
|
|
import logging
|
|
import socket
|
|
import threading
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
def _accept_loop(
|
|
server_sock: socket.socket,
|
|
clients: list,
|
|
lock: threading.Lock,
|
|
last_snapshot: dict,
|
|
) -> None:
|
|
while True:
|
|
try:
|
|
conn, addr = server_sock.accept()
|
|
log.info("Push client connected from %s", addr)
|
|
with lock:
|
|
if last_snapshot["data"] is not None:
|
|
try:
|
|
line = (json.dumps(last_snapshot["data"], default=str) + "\n").encode()
|
|
conn.sendall(line)
|
|
except OSError:
|
|
log.debug("Failed to send initial snapshot to %s", addr)
|
|
conn.close()
|
|
continue
|
|
clients.append(conn)
|
|
except OSError:
|
|
break
|
|
|
|
|
|
def broadcast(snapshot: dict, clients: list, lock: threading.Lock, last_snapshot: dict) -> None:
|
|
line = (json.dumps(snapshot, default=str) + "\n").encode()
|
|
with lock:
|
|
last_snapshot["data"] = snapshot
|
|
dead = []
|
|
for conn in clients:
|
|
try:
|
|
conn.sendall(line)
|
|
except OSError:
|
|
dead.append(conn)
|
|
for conn in dead:
|
|
clients.remove(conn)
|
|
conn.close()
|
|
log.info("Push client disconnected")
|
|
|
|
|
|
def start_push_server(host: str, port: int) -> tuple:
|
|
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
server_sock.bind((host, port))
|
|
server_sock.listen()
|
|
clients: list = []
|
|
lock = threading.Lock()
|
|
last_snapshot: dict = {"data": None}
|
|
t = threading.Thread(
|
|
target=_accept_loop,
|
|
args=(server_sock, clients, lock, last_snapshot),
|
|
daemon=True,
|
|
)
|
|
t.start()
|
|
log.info("Push server listening on %s:%d", host, port)
|
|
return clients, lock, last_snapshot |