[patch] 优化心跳检测逻辑 优化与后端交互连接处理逻辑 新增自动登录与手动下发冲突问题解决方法块

This commit is contained in:
2025-10-17 11:29:27 +08:00
parent e2ab13d599
commit 1438e39ffd
3 changed files with 132 additions and 26 deletions

View File

@@ -32,6 +32,7 @@ class BackendClient:
self.token_error_callback: Optional[Callable] = None # 新增token错误回调
self.version_callback: Optional[Callable] = None # 新增:版本检查回调
self.disconnect_callback: Optional[Callable] = None # 新增:被踢下线回调
self.log_callback: Optional[Callable] = None # 新增:日志回调
self.is_connected = False
@@ -47,6 +48,18 @@ class BackendClient:
self.loop = None
self.thread = None
def _log(self, message: str, level: str = "INFO"):
"""Unified logging method that works in both dev and packaged environments"""
# Always print to console (visible in dev mode)
print(f"[{level}] {message}")
# Also call the log callback if available (for file logging)
if self.log_callback:
try:
self.log_callback(message, level)
except Exception:
pass
def connect(self):
"""连接到WebSocket服务器"""
if self.is_connected:
@@ -90,7 +103,7 @@ class BackendClient:
"""连接并监听消息 - 带重连机制"""
while not self.should_stop:
try:
print(f"正在连接后端WebSocket: {self.url}")
self._log(f"正在连接后端WebSocket: {self.url}")
# 建立连接可配置的ping设置
from config import WS_PING_INTERVAL, WS_PING_TIMEOUT, WS_ENABLE_PING
@@ -106,7 +119,7 @@ class BackendClient:
max_queue=32, # 最大队列大小
compression=None # 禁用压缩以提高性能
)
print(f"[连接] 已启用心跳ping_interval={WS_PING_INTERVAL}s, ping_timeout={WS_PING_TIMEOUT}s")
self._log(f"已启用心跳ping_interval={WS_PING_INTERVAL}s, ping_timeout={WS_PING_TIMEOUT}s")
else:
self.websocket = await websockets.connect(
self.url,
@@ -114,12 +127,12 @@ class BackendClient:
max_queue=32,
compression=None
)
print("[连接] 已禁用心跳机制")
self._log("已禁用心跳机制", "WARNING")
self.is_connected = True
self.reconnect_attempts = 0 # 重置重连计数
self.is_reconnecting = False
print("后端WebSocket连接成功")
self._log("后端WebSocket连接成功", "SUCCESS")
# 等待连接稳定后再发送状态通知
await asyncio.sleep(0.5)
@@ -149,13 +162,13 @@ class BackendClient:
# 详细分析断开原因
if e.code == 1006:
print(f"[重连] WebSocket异常关闭 (1006): 可能是心跳超时或网络问题")
self._log("WebSocket异常关闭 (1006): 可能是心跳超时或网络问题", "WARNING")
elif e.code == 1000:
print(f"[重连] WebSocket正常关闭 (1000): 服务端主动断开")
self._log("WebSocket正常关闭 (1000): 服务端主动断开", "INFO")
elif e.code == 1001:
print(f"[重连] WebSocket关闭 (1001): 端点离开")
self._log("WebSocket关闭 (1001): 端点离开", "INFO")
else:
print(f"[重连] WebSocket关闭 ({e.code}): {e.reason}")
self._log(f"WebSocket关闭 ({e.code}): {e.reason}", "WARNING")
self._handle_connection_closed(e)
if not await self._should_reconnect():
@@ -185,14 +198,14 @@ class BackendClient:
def _handle_connection_closed(self, error):
"""处理连接关闭"""
error_msg = f"WebSocket连接已关闭: {error.code} {error.reason if hasattr(error, 'reason') else ''}"
print(f"[重连] {error_msg}")
self._log(error_msg, "WARNING")
# 特殊处理ping超时等情况
if hasattr(error, 'code'):
if error.code == 1011: # Internal error (ping timeout)
print("[重连] 检测到ping超时这是常见的网络问题")
self._log("检测到ping超时这是常见的网络问题", "WARNING")
elif error.code == 1006: # Abnormal closure
print("[重连] 检测到异常关闭,可能是网络中断")
self._log("检测到异常关闭,可能是网络中断或心跳超时", "WARNING")
if not self.is_reconnecting:
self.on_error(error_msg)
@@ -200,25 +213,25 @@ class BackendClient:
def _handle_network_error(self, error):
"""处理网络错误"""
error_msg = f"网络连接错误: {type(error).__name__} - {str(error)}"
print(f"[重连] {error_msg}")
self._log(error_msg, "ERROR")
if not self.is_reconnecting:
self.on_error(error_msg)
def _handle_general_error(self, error):
"""处理一般错误"""
error_msg = f"WebSocket连接异常: {type(error).__name__} - {str(error)}"
print(f"[重连] {error_msg}")
self._log(error_msg, "ERROR")
if not self.is_reconnecting:
self.on_error(error_msg)
async def _should_reconnect(self) -> bool:
"""判断是否应该重连"""
if self.should_stop:
print("[重连] 程序正在关闭,停止重连")
self._log("程序正在关闭,停止重连", "INFO")
return False
if self.reconnect_attempts >= self.max_reconnect_attempts:
print(f"[重连] 已达到最大重连次数({self.max_reconnect_attempts}),停止重连")
self._log(f"已达到最大重连次数({self.max_reconnect_attempts}),停止重连", "ERROR")
# 通知上层重连失败
if not self.is_reconnecting:
self.on_error(f"重连失败:已达到最大重连次数({self.max_reconnect_attempts})")
@@ -236,7 +249,7 @@ class BackendClient:
self.reconnect_attempts += 1
self.is_reconnecting = True
print(f"[重连] {self.reconnect_attempts}次重连尝试,等待{delay:.1f}秒...")
self._log(f"{self.reconnect_attempts}次重连尝试,等待{delay:.1f}秒...", "INFO")
# 分割等待时间,支持快速退出
wait_steps = max(1, int(delay))
@@ -267,7 +280,8 @@ class BackendClient:
success: Callable = None,
token_error: Callable = None,
version: Callable = None,
disconnect: Callable = None):
disconnect: Callable = None,
log: Callable = None):
"""设置各种消息类型的回调函数"""
if store_list:
self.store_list_callback = store_list
@@ -291,13 +305,15 @@ class BackendClient:
self.version_callback = version
if disconnect:
self.disconnect_callback = disconnect
if log:
self.log_callback = log
def on_connected(self):
"""连接成功时的处理"""
if self.reconnect_attempts > 0:
print(f"[重连] 后端WebSocket重连成功(第{self.reconnect_attempts}次尝试)")
self._log(f"后端WebSocket重连成功(第{self.reconnect_attempts}次尝试)", "SUCCESS")
else:
print("后端WebSocket连接成功")
self._log("后端WebSocket连接成功", "SUCCESS")
# 重连成功后可选择上报状态给后端
if self.reconnect_attempts > 0: