Files
aiagent/backend/app/websocket/manager.py
2026-01-19 00:09:36 +08:00

89 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
WebSocket连接管理器
"""
from typing import Dict, Set
from fastapi import WebSocket
import json
import asyncio
class WebSocketManager:
"""WebSocket连接管理器"""
def __init__(self):
"""初始化管理器"""
# execution_id -> Set[WebSocket]
self.active_connections: Dict[str, Set[WebSocket]] = {}
async def connect(self, websocket: WebSocket, execution_id: str):
"""
建立WebSocket连接
Args:
websocket: WebSocket连接
execution_id: 执行记录ID
"""
await websocket.accept()
if execution_id not in self.active_connections:
self.active_connections[execution_id] = set()
self.active_connections[execution_id].add(websocket)
def disconnect(self, websocket: WebSocket, execution_id: str):
"""
断开WebSocket连接
Args:
websocket: WebSocket连接
execution_id: 执行记录ID
"""
if execution_id in self.active_connections:
self.active_connections[execution_id].discard(websocket)
# 如果没有连接了删除该execution_id
if not self.active_connections[execution_id]:
del self.active_connections[execution_id]
async def send_personal_message(self, message: dict, websocket: WebSocket):
"""
发送个人消息
Args:
message: 消息内容
websocket: WebSocket连接
"""
try:
await websocket.send_json(message)
except Exception as e:
print(f"发送WebSocket消息失败: {e}")
async def broadcast_to_execution(self, execution_id: str, message: dict):
"""
向特定执行的所有连接广播消息
Args:
execution_id: 执行记录ID
message: 消息内容
"""
if execution_id not in self.active_connections:
return
# 需要断开连接的连接
disconnected = set()
for websocket in self.active_connections[execution_id]:
try:
await websocket.send_json(message)
except Exception as e:
print(f"广播消息失败: {e}")
disconnected.add(websocket)
# 移除断开的连接
for websocket in disconnected:
self.disconnect(websocket, execution_id)
# 全局WebSocket管理器实例
websocket_manager = WebSocketManager()