feat: 娣诲姞澶氫釜鏂板姛鑳藉拰淇 - 鍖呮嫭鐢ㄦ埛绠$悊銆佹暟鎹簱杩佺Щ銆丟it鎺ㄩ€佸伐鍏风瓑
This commit is contained in:
@@ -213,18 +213,22 @@ class WebSocketServer:
|
||||
|
||||
async def handle_client(self, websocket: WebSocketServerProtocol, path: str):
|
||||
"""处理客户端连接"""
|
||||
# 检查连接头
|
||||
headers = websocket.request_headers
|
||||
connection = headers.get("Connection", "").lower()
|
||||
|
||||
# 处理不同的连接头格式
|
||||
if "upgrade" not in connection and "keep-alive" in connection:
|
||||
logger.warning(f"收到非标准连接头: {connection}")
|
||||
# 对于keep-alive连接头,我们仍然接受连接
|
||||
elif "upgrade" not in connection:
|
||||
logger.warning(f"连接头不包含upgrade: {connection}")
|
||||
await websocket.close(code=1002, reason="Invalid connection header")
|
||||
return
|
||||
# 检查连接头(如果可用)
|
||||
try:
|
||||
if hasattr(websocket, 'request_headers'):
|
||||
headers = websocket.request_headers
|
||||
connection = headers.get("Connection", "").lower()
|
||||
|
||||
# 处理不同的连接头格式
|
||||
if "upgrade" not in connection and "keep-alive" in connection:
|
||||
logger.warning(f"收到非标准连接头: {connection}")
|
||||
# 对于keep-alive连接头,我们仍然接受连接
|
||||
elif "upgrade" not in connection:
|
||||
logger.warning(f"连接头不包含upgrade: {connection}")
|
||||
# 在websockets 15.x中,连接已经在serve时验证,所以这里只记录警告
|
||||
except AttributeError:
|
||||
# websockets 15.x版本可能没有request_headers属性,跳过检查
|
||||
pass
|
||||
|
||||
await self.register_client(websocket)
|
||||
|
||||
@@ -243,19 +247,15 @@ class WebSocketServer:
|
||||
logger.info(f"启动WebSocket服务器: ws://{self.host}:{self.port}")
|
||||
|
||||
# 添加CORS支持
|
||||
async def handle_client_with_cors(websocket: WebSocketServerProtocol, path: str):
|
||||
# 设置CORS头
|
||||
if websocket.request_headers.get("Origin"):
|
||||
# 允许跨域连接
|
||||
pass
|
||||
await self.handle_client(websocket, path)
|
||||
async def handle_client_with_cors(websocket: WebSocketServerProtocol, path: str = None):
|
||||
# CORS处理:websockets库默认允许所有来源连接
|
||||
# 如果需要限制,可以在serve时使用additional_headers参数
|
||||
await self.handle_client(websocket, path or "")
|
||||
|
||||
async with websockets.serve(
|
||||
handle_client_with_cors,
|
||||
self.host,
|
||||
self.port,
|
||||
# 添加额外的服务器选项
|
||||
process_request=self._process_request
|
||||
self.port
|
||||
):
|
||||
await asyncio.Future() # 保持服务器运行
|
||||
|
||||
|
||||
Reference in New Issue
Block a user