优化目前版本中的问题

This commit is contained in:
2025-03-10 13:56:25 +08:00
parent 758082db14
commit b4b1085403
11 changed files with 211 additions and 20 deletions

View File

@ -0,0 +1,37 @@
from fastapi import WebSocket
class SocketManager:
def __init__(self):
self.rooms = {}
async def add_to_room(self, room: str, websocket: WebSocket):
if room not in self.rooms:
self.rooms[room] = []
self.rooms[room].append(websocket)
async def remove_from_room(self, room: str, websocket: WebSocket):
if room in self.rooms:
self.rooms[room].remove(websocket)
if len(self.rooms[room]) == 0:
del self.rooms[room]
async def broadcast_to_room(self, room: str, message: str, exclude_websocket: WebSocket = None):
if room in self.rooms:
for ws in self.rooms[room]:
if ws != exclude_websocket:
try:
await ws.send_text(message)
except:
await self.remove_from_room(room, ws)
async def send_to_room(self, room: str, message: str):
if room in self.rooms:
for ws in self.rooms[room]:
try:
await ws.send_text(message)
except:
await self.remove_from_room(room, ws)
room_manager = SocketManager()