Browse Source

长连接与页面保活优化

yanqiliang 5 months ago
parent
commit
e187256f6d
2 changed files with 399 additions and 43 deletions
  1. 122 7
      src/api/index.js
  2. 277 36
      src/pages/home/Index.jsx

+ 122 - 7
src/api/index.js

@@ -417,6 +417,7 @@ const testSocket = (getMessage) => {
 
 let socketReconnectTimer = null;
 let socketReconnectKey = '';
+let lastSocketInitArgs = null;
 
 const clearSocketReconnectTimer = () => {
   if (socketReconnectTimer) {
@@ -426,6 +427,53 @@ const clearSocketReconnectTimer = () => {
   }
 };
 
+export const destroySocket = () => {
+  clearSocketReconnectTimer();
+  const oldSocket = window.socket;
+  if (!oldSocket) {
+    return;
+  }
+  window.socket = null;
+  try {
+    if (oldSocket.__cleanupHeartbeat) {
+      oldSocket.__cleanupHeartbeat();
+      oldSocket.__cleanupHeartbeat = null;
+    }
+  } catch (e) {
+    console.warn('清理 socket 心跳监听失败', e);
+  }
+  try {
+    if (oldSocket.removeAllListeners) {
+      oldSocket.removeAllListeners();
+    }
+  } catch (e) {
+    console.warn('清理 socket 监听失败', e);
+  }
+  try {
+    oldSocket.close();
+  } catch (e) {
+    console.warn('关闭 socket 失败', e);
+  }
+};
+
+export const forceRecreateSocket = (reason = '强制重建长连接') => {
+  if (!lastSocketInitArgs) {
+    destroySocket();
+    return false;
+  }
+  const { obj, getMessage, onSocketStatus } = lastSocketInitArgs;
+  destroySocket();
+  onSocketStatus &&
+    onSocketStatus({
+      visible: true,
+      status: 'recreating',
+      message: reason,
+      lastError: reason,
+    });
+  initSocket(obj, getMessage, onSocketStatus);
+  return true;
+};
+
 // scoket创建
 export const initSocket = (obj, getMessage, onSocketStatus) => {
   // 测试模拟发送消息start!!!!
@@ -434,10 +482,10 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
   // }
   // 测试模拟发送消息end!!!!
   const socketKey = `${obj.serverIP}:${obj.serverPort}:${obj.deviceID}`;
+  lastSocketInitArgs = { obj, getMessage, onSocketStatus };
   clearSocketReconnectTimer();
   if (window.socket && window.socket.__socketKey !== socketKey) {
-    window.socket.close();
-    window.socket = null;
+    destroySocket();
   }
   if (window.socket) {
     window.socket.__getMessage = getMessage;
@@ -462,8 +510,9 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
   }
   const MAX_RECONNECTION_ATTEMPTS = 20;
   const emitSocketStatus = (status) => {
-    onSocketStatus &&
-      onSocketStatus({
+    const statusHandler = window.socket?.__onSocketStatus || onSocketStatus;
+    statusHandler &&
+      statusHandler({
         maxAttempts: MAX_RECONNECTION_ATTEMPTS,
         ...status,
       });
@@ -476,11 +525,11 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
     reconnectionDelayMax: 5000,
     timeout: 20000,
     transports: ['websocket'],
-    forceNew: false,
     query: {
       type: 'C',
       deviceID: obj.deviceID,
     },
+    forceNew: true,
   });
   window.socket.__socketKey = socketKey;
   window.socket.__getMessage = getMessage;
@@ -492,6 +541,72 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
     }
     emitSocketStatus(status);
   };
+  const emitHeartbeatStatus = (eventName) => {
+    const now = Date.now();
+    const timeText = new Date(now).toLocaleTimeString('zh-CN', { hour12: false });
+    const status = {
+      event: eventName,
+      socketId: currentSocket.id || '',
+      socketConnected: !!currentSocket.connected,
+    };
+    if (eventName === 'ping') {
+      status.lastPingAt = timeText;
+      status.lastPingAtMs = now;
+    }
+    if (eventName === 'pong' || eventName === 'heartbeat') {
+      status.lastPongAt = timeText;
+      status.lastPongAtMs = now;
+      status.lastHeartbeatAt = timeText;
+      status.lastHeartbeatAtMs = now;
+    }
+    emitCurrentSocketStatus(status);
+  };
+  const bindEngineHeartbeat = () => {
+    const engine = currentSocket.io && currentSocket.io.engine;
+    if (!engine || currentSocket.__heartbeatEngine === engine) {
+      return;
+    }
+    currentSocket.__heartbeatEngine = engine;
+    const onPing = () => {
+      emitHeartbeatStatus('ping');
+    };
+    const onPong = () => {
+      emitHeartbeatStatus('pong');
+    };
+    const onHeartbeat = () => {
+      emitHeartbeatStatus('heartbeat');
+    };
+    engine.on('ping', onPing);
+    engine.on('pong', onPong);
+    engine.on('heartbeat', onHeartbeat);
+    currentSocket.__cleanupHeartbeat = () => {
+      if (currentSocket.io && currentSocket.io.off) {
+        currentSocket.io.off('open', bindEngineHeartbeat);
+      } else if (currentSocket.io && currentSocket.io.removeListener) {
+        currentSocket.io.removeListener('open', bindEngineHeartbeat);
+      }
+      if (engine.off) {
+        engine.off('ping', onPing);
+        engine.off('pong', onPong);
+        engine.off('heartbeat', onHeartbeat);
+      } else if (engine.removeListener) {
+        engine.removeListener('ping', onPing);
+        engine.removeListener('pong', onPong);
+        engine.removeListener('heartbeat', onHeartbeat);
+      }
+    };
+    emitCurrentSocketStatus({
+      event: 'heartbeat-bind',
+      socketId: currentSocket.id || '',
+      socketConnected: !!currentSocket.connected,
+      heartbeatIntervalMs: engine.pingInterval || 0,
+      heartbeatTimeoutMs: engine.pingTimeout || 0,
+    });
+  };
+  if (currentSocket.io && currentSocket.io.on) {
+    currentSocket.io.on('open', bindEngineHeartbeat);
+  }
+  setTimeout(bindEngineHeartbeat, 0);
   // window.socket = new WebSocket('http://m00.puruiit.cn:10015/socket.io/?type=C&deviceID=8e5604af-99db-47a5-b5e9-465040486690&EIO=4&transport=websocket');
   currentSocket.on('connect_timeout', function () {
     console.log('connect_timeout');
@@ -524,6 +639,7 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
   currentSocket.on('connect', function () {
     console.log('scoket连接成功');
     isRecreatingSocket = false;
+    bindEngineHeartbeat();
     emitCurrentSocketStatus({
       visible: false,
       status: 'connected',
@@ -602,8 +718,7 @@ export const initSocket = (obj, getMessage, onSocketStatus) => {
       message: '长连接重连失败,正在重新创建连接',
     });
     if (window.socket === failedSocket) {
-      failedSocket.close();
-      window.socket = null;
+      destroySocket();
     }
     emitSocketStatus({
       visible: true,

+ 277 - 36
src/pages/home/Index.jsx

@@ -5,7 +5,7 @@ import BigScreen from '@pages/bigScreen/Index.jsx';
 import BigScreenOld from '@pages/bigScreen/IndexOld.jsx';
 import OperateScreen from '@pages/operateScreen/Index.jsx';
 import FingerprintJS from '@fingerprintjs/fingerprintjs';
-import { initSocket } from '@api/index.js';
+import { forceRecreateSocket as recreateSocket, initSocket } from '@api/index.js';
 import { AntOutline, ContentOutline, SetOutline } from 'antd-mobile-icons';
 import { Modal } from 'antd-mobile';
 
@@ -17,6 +17,14 @@ class Home extends React.Component {
   AUDIO_PLAYING_TIMEOUT_MS = 20000; // 已开始播放后最多等待 20s 兜底
   LEGACY_AUDIO_TOTAL_TIMEOUT_MS = 30000; // 旧APK无playId回调,保留较宽兜底兼容现网
   MAX_VOICE_QUEUE = 50;       // 语音队列最大长度,洪峰场景丢最早的,避免无限增长
+  HEARTBEAT_TIMEOUT_MS = 45 * 1000; // 45s 无 pong/heartbeat 即认为底层心跳异常
+  BUSINESS_SILENT_MS = 10 * 60 * 1000; // 10min 无 callNumber 即疑似业务静默
+  HEARTBEAT_RECREATE_COOLDOWN_MS = 60 * 1000;
+  BUSINESS_RECREATE_COOLDOWN_MS = 10 * 60 * 1000;
+  BUSINESS_RECREATE_WINDOW_MS = 60 * 60 * 1000;
+  BUSINESS_RECREATE_MAX_PER_WINDOW = 3;
+  ANDROID_RECREATE_COOLDOWN_MS = 60 * 1000;
+  DEBUG_TICK_INTERVAL_MS = 10 * 1000;
 
   constructor(props) {
     super(props);
@@ -61,6 +69,19 @@ class Home extends React.Component {
         lastDisconnectAt: '',
         lastDisconnectReason: '',
         reconnectAttempt: 0,
+        lastPingAt: '',
+        lastPingAtMs: 0,
+        lastPongAt: '',
+        lastPongAtMs: 0,
+        lastHeartbeatAt: '',
+        lastHeartbeatAtMs: 0,
+        heartbeatBound: false,
+        heartbeatIntervalMs: 0,
+        heartbeatTimeoutMs: 0,
+        autoRecreateCount: 0,
+        lastRecreateAt: '',
+        lastRecreateAtMs: 0,
+        lastRecreateReason: '',
         receiveCount: 0,
         lastReceiveAt: '',
         lastReceiveAtMs: 0,
@@ -90,6 +111,14 @@ class Home extends React.Component {
     this.isAudioBusy = false;
     this.ignoreNextLegacyAudioCallback = false;
     this.debugTickTimer = null;
+    this.lastHeartbeatRecreateAt = 0;
+    this.lastBusinessRecreateAt = 0;
+    this.businessRecreateWindowStartAt = 0;
+    this.businessRecreateCountInWindow = 0;
+    this.previousWindowOnError = null;
+    this.previousWindowOnUnhandledRejection = null;
+    this.windowOnErrorHandler = null;
+    this.windowOnUnhandledRejectionHandler = null;
   }
 
   getNowTime = () => new Date().toLocaleTimeString('zh-CN', { hour12: false });
@@ -123,18 +152,39 @@ class Home extends React.Component {
     this.formatDuration(this.getSilentDurationMs(debugInfo))
   );
 
+  getHeartbeatSilentDurationMs = (debugInfo = this.state.debugInfo) => {
+    if (!debugInfo.heartbeatBound) {
+      return null;
+    }
+    const baseTime = Math.max(
+      debugInfo.lastPongAtMs || 0,
+      debugInfo.lastHeartbeatAtMs || 0,
+      debugInfo.lastConnectAtMs || 0,
+    );
+    if (!baseTime) {
+      return null;
+    }
+    return Math.max(0, (debugInfo.debugNowAt || Date.now()) - baseTime);
+  };
+
+  getHeartbeatSilentDurationText = (debugInfo = this.state.debugInfo) => (
+    this.formatDuration(this.getHeartbeatSilentDurationMs(debugInfo))
+  );
+
   startDebugTicker = () => {
     if (this.debugTickTimer) {
       clearInterval(this.debugTickTimer);
     }
     this.debugTickTimer = setInterval(() => {
+      const now = Date.now();
       this.setState((prevState) => ({
         debugInfo: {
           ...prevState.debugInfo,
-          debugNowAt: Date.now(),
+          debugNowAt: now,
         },
       }));
-    }, 30000);
+      this.checkSocketHealth(now);
+    }, this.DEBUG_TICK_INTERVAL_MS);
   };
 
   getSocketId = () => {
@@ -211,6 +261,189 @@ class Home extends React.Component {
     }));
   };
 
+  canUseBusinessRecreate = (now) => {
+    if (!this.businessRecreateWindowStartAt || now - this.businessRecreateWindowStartAt >= this.BUSINESS_RECREATE_WINDOW_MS) {
+      this.businessRecreateWindowStartAt = now;
+      this.businessRecreateCountInWindow = 0;
+    }
+    if (this.businessRecreateCountInWindow >= this.BUSINESS_RECREATE_MAX_PER_WINDOW) {
+      this.updateDebugInfo(null, {
+        type: 'socket',
+        message: `业务静默重建已达每小时上限 ${this.BUSINESS_RECREATE_MAX_PER_WINDOW} 次`,
+      });
+      return false;
+    }
+    this.businessRecreateCountInWindow += 1;
+    return true;
+  };
+
+  forceRecreateSocket = (reason, options = {}) => {
+    const now = options.now || Date.now();
+    const isBusinessSilent = options.type === 'business-silent';
+    const cooldownMs = options.cooldownMs || this.HEARTBEAT_RECREATE_COOLDOWN_MS;
+    const lastRecreateAt = isBusinessSilent
+      ? this.lastBusinessRecreateAt
+      : this.lastHeartbeatRecreateAt;
+    if (options.auto && lastRecreateAt && now - lastRecreateAt < cooldownMs) {
+      this.updateDebugInfo(null, {
+        type: 'socket',
+        message: `跳过重建,仍在冷却期: ${reason}`,
+      });
+      return false;
+    }
+    if (options.auto && isBusinessSilent && !this.canUseBusinessRecreate(now)) {
+      return false;
+    }
+    if (isBusinessSilent) {
+      this.lastBusinessRecreateAt = now;
+    } else {
+      this.lastHeartbeatRecreateAt = now;
+    }
+    this.updateDebugInfo((debugInfo) => ({
+      socketStatus: 'recreating',
+      socketConnected: false,
+      autoRecreateCount: debugInfo.autoRecreateCount + (options.auto ? 1 : 0),
+      lastRecreateAt: this.getNowTime(),
+      lastRecreateAtMs: now,
+      lastRecreateReason: reason,
+      debugNowAt: now,
+    }), {
+      type: 'socket',
+      message: `强制重建长连接: ${reason}`,
+    });
+    const recreated = recreateSocket(reason);
+    if (!recreated) {
+      this.loginInit();
+    }
+    return recreated;
+  };
+
+  checkSocketHealth = (now = Date.now()) => {
+    const { debugInfo, visibleLogin } = this.state;
+    if (visibleLogin) {
+      return;
+    }
+    const connected = this.getSocketConnected() || debugInfo.socketConnected;
+    if (!connected) {
+      return;
+    }
+    const heartbeatSilentMs = this.getHeartbeatSilentDurationMs({
+      ...debugInfo,
+      debugNowAt: now,
+    });
+    if (
+      debugInfo.heartbeatBound &&
+      heartbeatSilentMs !== null &&
+      heartbeatSilentMs >= this.HEARTBEAT_TIMEOUT_MS
+    ) {
+      this.forceRecreateSocket(
+        `心跳静默超过 ${this.formatDuration(this.HEARTBEAT_TIMEOUT_MS)},强制重建长连接`,
+        {
+          auto: true,
+          type: 'heartbeat-timeout',
+          cooldownMs: this.HEARTBEAT_RECREATE_COOLDOWN_MS,
+          now,
+        },
+      );
+      return;
+    }
+    const businessSilentMs = this.getSilentDurationMs({
+      ...debugInfo,
+      debugNowAt: now,
+    });
+    if (businessSilentMs !== null && businessSilentMs >= this.BUSINESS_SILENT_MS) {
+      this.forceRecreateSocket(
+        `业务静默超过 ${this.formatDuration(this.BUSINESS_SILENT_MS)},疑似假在线,温和重建长连接`,
+        {
+          auto: true,
+          type: 'business-silent',
+          cooldownMs: this.BUSINESS_RECREATE_COOLDOWN_MS,
+          now,
+        },
+      );
+    }
+  };
+
+  getCallAppHealth = () => {
+    const { debugInfo, voiceList, visibleLogin } = this.state;
+    return {
+      aliveAt: Date.now(),
+      pageTickAt: debugInfo.debugNowAt || 0,
+      visibleLogin,
+      deviceID: this.state.deviceID,
+      socketConnected: this.getSocketConnected(),
+      socketStatus: debugInfo.socketStatus,
+      socketId: this.getSocketId(),
+      lastConnectAtMs: debugInfo.lastConnectAtMs || 0,
+      lastReceiveAtMs: debugInfo.lastReceiveAtMs || 0,
+      lastPongAtMs: debugInfo.lastPongAtMs || 0,
+      lastHeartbeatAtMs: debugInfo.lastHeartbeatAtMs || 0,
+      receiveCount: debugInfo.receiveCount,
+      voiceQueueLength: voiceList.length,
+      isAudioBusy: this.isAudioBusy,
+      lastAudioStatus: debugInfo.lastAudioStatus,
+      lastAudioError: debugInfo.lastAudioError,
+      lastError: debugInfo.lastDisconnectReason,
+    };
+  };
+
+  installWatchdogBridge = () => {
+    window.__CALLAPP_HEALTH__ = () => this.getCallAppHealth();
+    window.__CALLAPP_FORCE_RECREATE_SOCKET__ = (reason = 'Android watchdog 强制重建长连接') => (
+      this.forceRecreateSocket(reason, {
+        auto: true,
+        type: 'android-watchdog',
+        cooldownMs: this.ANDROID_RECREATE_COOLDOWN_MS,
+      })
+    );
+  };
+
+  installRuntimeDiagnostics = () => {
+    this.previousWindowOnError = window.onerror;
+    this.previousWindowOnUnhandledRejection = window.onunhandledrejection;
+    this.windowOnErrorHandler = (message, source, lineno, colno, error) => {
+      this.updateDebugInfo({
+        lastDisconnectReason: error?.message || String(message || ''),
+      }, {
+        type: 'js',
+        message: `运行错误: ${error?.message || message || '-'} @${lineno || '-'}:${colno || '-'}`,
+      });
+      if (typeof this.previousWindowOnError === 'function') {
+        return this.previousWindowOnError(message, source, lineno, colno, error);
+      }
+      return false;
+    };
+    this.windowOnUnhandledRejectionHandler = (event) => {
+      const reason = event?.reason;
+      const message = reason?.message || String(reason || 'unhandled rejection');
+      this.updateDebugInfo({
+        lastDisconnectReason: message,
+      }, {
+        type: 'js',
+        message: `未处理Promise: ${message}`,
+      });
+      if (typeof this.previousWindowOnUnhandledRejection === 'function') {
+        return this.previousWindowOnUnhandledRejection(event);
+      }
+      return false;
+    };
+    window.onerror = this.windowOnErrorHandler;
+    window.onunhandledrejection = this.windowOnUnhandledRejectionHandler;
+  };
+
+  cleanupRuntimeDiagnostics = () => {
+    if (window.onerror === this.windowOnErrorHandler) {
+      window.onerror = this.previousWindowOnError || null;
+    }
+    if (window.onunhandledrejection === this.windowOnUnhandledRejectionHandler) {
+      window.onunhandledrejection = this.previousWindowOnUnhandledRejection || null;
+    }
+    this.previousWindowOnError = null;
+    this.previousWindowOnUnhandledRejection = null;
+    this.windowOnErrorHandler = null;
+    this.windowOnUnhandledRejectionHandler = null;
+  };
+
   renderDebugRow = (label, value, className = '') => (
     <div className="debug-row">
       <span className="debug-label">{label}</span>
@@ -236,6 +469,10 @@ class Home extends React.Component {
             {this.renderDebugRow('最后断开', debugInfo.lastDisconnectAt)}
             {this.renderDebugRow('断开原因', debugInfo.lastDisconnectReason, 'long')}
             {this.renderDebugRow('重连次数', debugInfo.reconnectAttempt)}
+            {this.renderDebugRow('最后Pong', debugInfo.lastPongAt)}
+            {this.renderDebugRow('心跳静默', this.getHeartbeatSilentDurationText(debugInfo))}
+            {this.renderDebugRow('自动重建', debugInfo.autoRecreateCount)}
+            {this.renderDebugRow('重建原因', debugInfo.lastRecreateReason, 'long')}
           </div>
           <div className="debug-section">
             <div className="debug-section-title">消息接收</div>
@@ -276,6 +513,8 @@ class Home extends React.Component {
   };
 
   componentDidMount() {
+    this.installRuntimeDiagnostics();
+    this.installWatchdogBridge();
     this.startDebugTicker();
     this.initDevice();
     this.initAndroidVoice();
@@ -292,6 +531,9 @@ class Home extends React.Component {
       if (window.mediaPlayOver) window.mediaPlayOver = undefined;
       if (window.mediaPlayStatus) window.mediaPlayStatus = undefined;
       if (window.onNativeReady) window.onNativeReady = undefined;
+      if (window.__CALLAPP_HEALTH__) window.__CALLAPP_HEALTH__ = undefined;
+      if (window.__CALLAPP_FORCE_RECREATE_SOCKET__) window.__CALLAPP_FORCE_RECREATE_SOCKET__ = undefined;
+      this.cleanupRuntimeDiagnostics();
     } catch (e) {
       console.warn('清理全局桥接回调失败', e);
     }
@@ -711,30 +953,53 @@ class Home extends React.Component {
   handleSocketStatus = (status = {}) => {
     const updatedAt = new Date().toLocaleTimeString('zh-CN', { hour12: false });
     const updatedAtMs = Date.now();
+    const hasSocketStatus = !!status.status;
     const socketStatus = status.status || this.state.debugInfo.socketStatus;
     const socketId = status.socketId || this.getSocketId();
     const socketConnected = this.getSocketConnected() || socketStatus === 'connected';
     const debugPatch = {
       socketStatus,
-      socketConnected,
+      socketConnected: status.socketConnected ?? socketConnected,
       socketId,
     };
     let log = null;
-    if (socketStatus === 'connected') {
+    if (status.event === 'ping') {
+      debugPatch.heartbeatBound = true;
+      debugPatch.lastPingAt = status.lastPingAt || updatedAt;
+      debugPatch.lastPingAtMs = status.lastPingAtMs || updatedAtMs;
+      debugPatch.debugNowAt = updatedAtMs;
+    }
+    if (status.event === 'pong' || status.event === 'heartbeat') {
+      debugPatch.heartbeatBound = true;
+      debugPatch.lastPongAt = status.lastPongAt || updatedAt;
+      debugPatch.lastPongAtMs = status.lastPongAtMs || updatedAtMs;
+      debugPatch.lastHeartbeatAt = status.lastHeartbeatAt || updatedAt;
+      debugPatch.lastHeartbeatAtMs = status.lastHeartbeatAtMs || updatedAtMs;
+      debugPatch.debugNowAt = updatedAtMs;
+    }
+    if (status.event === 'heartbeat-bind') {
+      debugPatch.heartbeatBound = true;
+      debugPatch.heartbeatIntervalMs = status.heartbeatIntervalMs || 0;
+      debugPatch.heartbeatTimeoutMs = status.heartbeatTimeoutMs || 0;
+    }
+    if (hasSocketStatus && socketStatus === 'connected') {
       debugPatch.lastConnectAt = updatedAt;
       debugPatch.lastConnectAtMs = updatedAtMs;
       debugPatch.debugNowAt = updatedAtMs;
       debugPatch.lastDisconnectReason = '';
       debugPatch.reconnectAttempt = status.attempt || 0;
       log = { type: 'socket', message: `连接成功 ${socketId || ''}`.trim() };
-    } else if (socketStatus === 'disconnected') {
+    } else if (hasSocketStatus && socketStatus === 'disconnected') {
       debugPatch.lastDisconnectAt = updatedAt;
       debugPatch.lastDisconnectReason = status.lastError || '';
       log = { type: 'socket', message: `连接断开: ${status.lastError || '-'}` };
-    } else if (socketStatus === 'reconnecting') {
+    } else if (hasSocketStatus && socketStatus === 'reconnecting') {
       debugPatch.reconnectAttempt = status.attempt || this.state.debugInfo.reconnectAttempt;
       log = { type: 'socket', message: status.message || '长连接重连中' };
-    } else if (socketStatus === 'error' || socketStatus === 'failed' || socketStatus === 'timeout') {
+    } else if (
+      hasSocketStatus &&
+      (socketStatus === 'error' || socketStatus === 'failed' || socketStatus === 'timeout')
+    ) {
       debugPatch.lastDisconnectReason = status.lastError || status.message || '';
       log = { type: 'socket', message: status.message || socketStatus };
     }
@@ -751,35 +1016,11 @@ class Home extends React.Component {
     this.handleSocketStatus({ visible: false });
   };
   reconnectSocket = () => {
-    if (window.socket) {
-      if (window.socket.connected) {
-        this.handleSocketStatus({
-          visible: false,
-          status: 'connected',
-          message: '长连接已连接',
-          lastError: '',
-        });
-        this.updateDebugInfo(null, {
-          type: 'socket',
-          message: '手动重连时 socket 仍显示已连接',
-        });
-        return;
-      }
-      window.socket.connect();
-      this.handleSocketStatus({
-        visible: true,
-        status: 'reconnecting',
-        message: '正在重新连接长连接',
-      });
-      return;
-    }
-    // window.socket 为空(reconnect_failed 已销毁实例)时,必须走完整重建流程
-    this.handleSocketStatus({
-      visible: true,
-      status: 'recreating',
-      message: '长连接已销毁,正在重新创建',
+    this.forceRecreateSocket('手动强制重建长连接', {
+      auto: false,
+      type: 'manual',
+      cooldownMs: 0,
     });
-    this.loginInit();
   };
   loginInit = async () => {
     let cache = localStorage.getItem('ZZJ-base');