askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
websocket.py · 1.3 KB · 47 lines
| 1 | """WebSocket room management""" |
| 2 | import json |
| 3 | from typing import Dict, Set |
| 4 | |
| 5 | |
| 6 | class WebSocketHub: |
| 7 | """Manage WebSocket connections and rooms""" |
| 8 | |
| 9 | def __init__(self): |
| 10 | self.rooms: Dict[str, Set] = {} |
| 11 | |
| 12 | async def join(self, room: str, ws): |
| 13 | """Add a WebSocket connection to a room""" |
| 14 | self.rooms.setdefault(room, set()).add(ws) |
| 15 | |
| 16 | async def leave(self, room: str, ws): |
| 17 | """Remove a WebSocket connection from a room""" |
| 18 | if room in self.rooms: |
| 19 | self.rooms[room].discard(ws) |
| 20 | if not self.rooms[room]: |
| 21 | del self.rooms[room] |
| 22 | |
| 23 | async def broadcast(self, room: str, event: dict): |
| 24 | """Broadcast an event to all connections in a room""" |
| 25 | if room not in self.rooms: |
| 26 | return |
| 27 | |
| 28 | dead = [] |
| 29 | message = json.dumps(event) |
| 30 | |
| 31 | for ws in self.rooms[room]: |
| 32 | try: |
| 33 | await ws.send_text(message) |
| 34 | except Exception: |
| 35 | dead.append(ws) |
| 36 | |
| 37 | # Clean up dead connections |
| 38 | for ws in dead: |
| 39 | await self.leave(room, ws) |
| 40 | |
| 41 | def get_room_count(self, room: str) -> int: |
| 42 | """Get the number of connections in a room""" |
| 43 | return len(self.rooms.get(room, set())) |
| 44 | |
| 45 | |
| 46 | # Global hub instance |
| 47 | hub = WebSocketHub() |