feat(chat): 完善聊天

This commit is contained in:
xingc
2025-04-16 14:44:52 +08:00
parent 02a1589833
commit e3f28ad67c
5 changed files with 110 additions and 79 deletions

View File

@@ -10,6 +10,7 @@ import logging
import redis.asyncio as aioredis
import ujson
from fastapi import WebSocket
from fastapi.websockets import WebSocketState
from core.db.engine import get_cache
@@ -72,7 +73,7 @@ class SocketManager:
self.chats[chat_guid] = {websocket}
await self.pubsub_client.connect()
pubsub_subscriber = await self.pubsub_client.subscribe(chat_guid)
await asyncio.create_task(self._pubsub_data_reader(pubsub_subscriber))
asyncio.create_task(self._pubsub_data_reader(pubsub_subscriber))
async def broadcast_to_chat(self, chat_guid: str, message: str | dict) -> None:
if isinstance(message, dict):
@@ -100,6 +101,8 @@ class SocketManager:
sockets = self.chats.get(chat_guid)
if sockets:
for socket in sockets:
if socket.client_state != WebSocketState.CONNECTED:
continue
data = message['data']
await socket.send_text(data)
else:
@@ -109,7 +112,8 @@ class SocketManager:
logger.exception(f'Exception occurred: {exc}')
async def send_error(self, message: str, websocket: WebSocket):
await websocket.send_json({'status': 'error', 'message': message})
if websocket.client_state == WebSocketState.CONNECTED:
await websocket.send_json({'status': 'error', 'content': message})
async def quit(self):
self._task_cancel = False