Files
MultiChatOverlay/websocket_manager.py

22 lines
898 B
Python

from typing import Dict, List
from fastapi import WebSocket
class WebSocketManager:
def __init__(self):
# Maps user_id to a list of active WebSocket connections
self.active_connections: Dict[int, List[WebSocket]] = {}
print("WebSocketManager initialized.")
async def connect(self, user_id: int, websocket: WebSocket):
await websocket.accept()
if user_id not in self.active_connections:
self.active_connections[user_id] = []
self.active_connections[user_id].append(websocket)
def disconnect(self, user_id: int, websocket: WebSocket):
self.active_connections[user_id].remove(websocket)
async def broadcast_to_user(self, user_id: int, message: dict):
if user_id in self.active_connections:
for connection in self.active_connections[user_id]:
await connection.send_json(message)