from typing import Dict, List from fastapi import WebSocket import json class ConnectionManager: def __init__(self): self.active_connections: Dict[str, List[WebSocket]] = {} async def connect(self, websocket: WebSocket, channel: str): await websocket.accept() if channel not in self.active_connections: self.active_connections[channel] = [] self.active_connections[channel].append(websocket) def disconnect(self, websocket: WebSocket, channel: str): if channel in self.active_connections: try: self.active_connections[channel].remove(websocket) except ValueError: pass async def broadcast(self, channel: str, data: dict): if channel not in self.active_connections: return dead = [] for ws in self.active_connections[channel]: try: await ws.send_json(data) except Exception: dead.append(ws) for ws in dead: self.disconnect(ws, channel) async def broadcast_all(self, data: dict): for channel in list(self.active_connections.keys()): await self.broadcast(channel, data) manager = ConnectionManager()