| 7 | |
| 8 | |
| 9 | class ConnectionManager: |
| 10 | def __init__(self): |
| 11 | self.user_counter = AtomicCounter() |
| 12 | self.active_connections = dict() |
| 13 | |
| 14 | async def connect(self, websocket: WebSocket): |
| 15 | await websocket.accept() |
| 16 | client_id = self.user_counter.inc() |
| 17 | self.active_connections[client_id] = websocket |
| 18 | |
| 19 | def disconnect(self, websocket: WebSocket): |
| 20 | k = self.client_id(websocket) |
| 21 | if k: |
| 22 | del self.active_connections[k] |
| 23 | |
| 24 | def client_id(self, websocket: WebSocket): |
| 25 | return next((uid for uid, ws in self.active_connections.items() if ws == websocket), None) |
| 26 | |
| 27 | async def broadcast(self, message: str, websocket): |
| 28 | for connection in filter(lambda c: c != websocket, self.active_connections.values()): |
| 29 | await connection.send_text(message) |
| 30 | |
| 31 | |
| 32 | manager = ConnectionManager() |