Spaces:
Runtime error
Runtime error
File size: 1,594 Bytes
69b17de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | from fastapi import WebSocket
from typing import List
import json
import logging
logger = logging.getLogger(__name__)
class ConnectionManager:
def __init__(self):
# Store active websocket connections
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
logger.info(f"WebSocket connected. Total connections: {len(self.active_connections)}")
def disconnect(self, websocket: WebSocket):
if websocket in self.active_connections:
self.active_connections.remove(websocket)
logger.info(f"WebSocket disconnected. Total connections: {len(self.active_connections)}")
async def broadcast(self, message: dict):
"""
Broadcast a JSON message to all connected clients.
If a connection is dropped, catch the exception and remove it.
"""
if not self.active_connections:
return
json_msg = json.dumps(message)
dead_connections = []
for connection in self.active_connections:
try:
await connection.send_text(json_msg)
except Exception as e:
logger.error(f"Error broadcasting to a client: {e}")
dead_connections.append(connection)
# Clean up any connections that failed
for dead in dead_connections:
self.disconnect(dead)
# Singleton instance to be used across the app
manager = ConnectionManager()
|