1
wwl
21 小时以前 0000e935d6c7f74cb6682aea1bbf24d8deade390
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// src/utils/websocket.js
let ws = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
const reconnectInterval = 5000; // 5秒重连间隔
const pingInterval = 5000; // 5秒发送ping
 
export function initWebSocket(token, onMessage) {
  if (!token) {
    console.error('WebSocket 初始化失败:缺少 token');
    return;
  }
 
  const wsUrl = `ws://192.168.1.2:5011/ws?token=${token}`;
  ws = new WebSocket(wsUrl);
 
  ws.onopen = () => {
    console.log('WebSocket 连接成功');
    reconnectAttempts = 0;
 
    // 启动心跳机制
    const pingTimer = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        console.log('发送 ping 消息');
        ws.send('ping');
      } else {
        console.warn('WebSocket 未连接,停止 ping');
        clearInterval(pingTimer);
      }
    }, pingInterval);
  };
 
  ws.onmessage = (event) => {
    const data = event.data;
    console.log('WebSocket 收到原始消息:', data);
    if (data === 'pong') {
      console.log('收到 pong 响应,连接活跃');
      return;
    }
    onMessage('message', data);
  };
 
  ws.onerror = (error) => {
    console.error('WebSocket 错误:', error);
    onMessage('error', 'WebSocket 连接错误');
  };
 
  ws.onclose = () => {
    console.warn('WebSocket 连接关闭');
    if (reconnectAttempts < maxReconnectAttempts) {
      reconnectAttempts++;
      console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
      setTimeout(() => {
        initWebSocket(token, onMessage);
      }, reconnectInterval);
    } else {
      console.error('达到最大重连次数,停止重连');
      onMessage('error', 'WebSocket 连接失败,已达最大重连次数');
    }
  };
 
  // 清理 WebSocket
  window.addEventListener('beforeunload', () => {
    if (ws) {
      ws.close();
      ws = null;
      console.log('WebSocket 已清理');
    }
  });
}
 
export function closeWebSocket() {
  if (ws) {
    ws.close();
    ws = null;
    console.log('WebSocket 已关闭');
  }
}