1
wwl
4 天以前 55ed081b8414698e6e3b7d76c5c4032f264fb53f
src/utils/websocket.js
@@ -1,6 +1,7 @@
// src/utils/websocket.js
let ws = null;
let reconnectAttempts = 0;
let pingTimer = null; // 用于管理心跳定时器
const maxReconnectAttempts = 5;
const reconnectInterval = 5000; // 5秒重连间隔
const pingInterval = 5000; // 5秒发送ping
@@ -11,21 +12,33 @@
    return;
  }
  const wsUrl = `ws://192.168.1.2:5011/ws?token=${token}`;
  // 如果 ws 已存在且连接活跃,则跳过初始化
  if (ws && ws.readyState === WebSocket.OPEN) {
    console.log('WebSocket 已连接,跳过重复初始化');
    return;
  }
  // 如果 ws 存在但未关闭,先关闭旧连接
  if (ws) {
    console.warn('发现旧 WebSocket 连接,正在关闭...');
    closeWebSocket();
  }
  const wsUrl = `ws://192.168.1.244:5011/ws?token=${token}`;
  ws = new WebSocket(wsUrl);
  ws.onopen = () => {
    console.log('WebSocket 连接成功');
    reconnectAttempts = 0;
    reconnectAttempts = 0; // 重置重连计数
    // 启动心跳机制
    const pingTimer = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        console.log('发送 ping 消息');
    if (pingTimer) clearInterval(pingTimer); // 清理旧定时器
    pingTimer = setInterval(() => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send('ping');
      } else {
        console.warn('WebSocket 未连接,停止 ping');
        clearInterval(pingTimer);
        pingTimer = null;
      }
    }, pingInterval);
  };
@@ -35,6 +48,7 @@
    console.log('WebSocket 收到原始消息:', data);
    if (data === 'pong') {
      console.log('收到 pong 响应,连接活跃');
      reconnectAttempts = 0; // 重置重连计数,确保活跃连接不触发重连
      return;
    }
    onMessage('message', data);
@@ -42,11 +56,14 @@
  ws.onerror = (error) => {
    console.error('WebSocket 错误:', error);
    onMessage('error', 'WebSocket 连接错误');
  };
  ws.onclose = () => {
    console.warn('WebSocket 连接关闭');
    console.warn('WebSocket 连接关闭,时间:', new Date());
    if (pingTimer) {
      clearInterval(pingTimer);
      pingTimer = null;
    }
    if (reconnectAttempts < maxReconnectAttempts) {
      reconnectAttempts++;
      console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
@@ -61,18 +78,18 @@
  // 清理 WebSocket
  window.addEventListener('beforeunload', () => {
    if (ws) {
      ws.close();
      ws = null;
      console.log('WebSocket 已清理');
    }
  });
    closeWebSocket();
  }, { once: true }); // 确保事件监听只添加一次
}
export function closeWebSocket() {
  if (ws) {
    ws.close();
    ws = null;
    if (pingTimer) {
      clearInterval(pingTimer);
      pingTimer = null;
    }
    console.log('WebSocket 已关闭');
  }
}