fix: WebSocket断开后正确退出循环
This commit is contained in:
+20
@@ -530,7 +530,27 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
|
try:
|
||||||
data = await websocket.receive_json()
|
data = await websocket.receive_json()
|
||||||
|
except Exception as json_err:
|
||||||
|
logger.error(f"JSON解析错误: {json_err}")
|
||||||
|
# 如果连接已断开,退出循环
|
||||||
|
if "disconnect" in str(json_err).lower() or "closed" in str(json_err).lower():
|
||||||
|
logger.info("WebSocket已断开,退出循环")
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
text_data = await websocket.receive_text()
|
||||||
|
if text_data.strip():
|
||||||
|
data = json.loads(text_data)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
except Exception as text_err:
|
||||||
|
logger.error(f"文本消息解析错误: {text_err}")
|
||||||
|
if "disconnect" in str(text_err).lower() or "closed" in str(text_err).lower():
|
||||||
|
logger.info("WebSocket已断开,退出循环")
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
|
||||||
action = data.get("action")
|
action = data.get("action")
|
||||||
logger.info(f"WebSocket收到消息: action={action}")
|
logger.info(f"WebSocket收到消息: action={action}")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user