scamdetect-backend / backend /api /ws_manager.py
ScamDetect Bot
Auto-sync backend from GitHub
69b17de
Raw
History Blame Contribute Delete
1.59 kB
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()