24 lines
962 B
Python
24 lines
962 B
Python
from typing import Dict, List
|
|
from fastapi import WebSocket
|
|
|
|
class WebSocketManager:
|
|
def __init__(self):
|
|
self.active_connections: Dict[int, List[WebSocket]] = {}
|
|
|
|
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):
|
|
if user_id in self.active_connections:
|
|
self.active_connections[user_id].remove(websocket)
|
|
if not self.active_connections[user_id]:
|
|
del self.active_connections[user_id]
|
|
|
|
async def send_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)
|