43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
import json
|
|
import logging
|
|
from typing import List, Dict, Any
|
|
from fastapi import WebSocket
|
|
|
|
logger = logging.getLogger("AuraTrade.ConnectionManager")
|
|
|
|
class ConnectionManager:
|
|
"""
|
|
High-Frequency WebSocket Connection Hub
|
|
Broadcasts sub-20ms ticks, telemetry, and signals to connected web clients.
|
|
"""
|
|
def __init__(self):
|
|
self.active_connections: List[WebSocket] = []
|
|
|
|
async def connect(self, websocket: WebSocket):
|
|
await websocket.accept()
|
|
self.active_connections.append(websocket)
|
|
logger.info(f"Client connected. Active terminals: {len(self.active_connections)}")
|
|
|
|
def disconnect(self, websocket: WebSocket):
|
|
if websocket in self.active_connections:
|
|
self.active_connections.remove(websocket)
|
|
logger.info(f"Client disconnected. Active terminals: {len(self.active_connections)}")
|
|
|
|
async def broadcast_json(self, message: Dict[str, Any]):
|
|
"""Broadcasts a JSON packet to all connected web terminals."""
|
|
if not self.active_connections:
|
|
return
|
|
|
|
payload = json.dumps(message)
|
|
dead_connections = []
|
|
for connection in self.active_connections:
|
|
try:
|
|
await connection.send_text(payload)
|
|
except Exception:
|
|
dead_connections.append(connection)
|
|
|
|
for dead in dead_connections:
|
|
self.disconnect(dead)
|
|
|
|
ws_manager = ConnectionManager()
|