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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<template>
<div id="app">
<router-view />
</div>
</template>

<script>
export default {
name: 'App',
data() {
return {
socket: null,
retryCount: 0,
isReconnecting: false,
heartbeatTimer: null,
};
},
created() {
this.connectWebSocket();
},
beforeUnmount() {
if (this.socket) {
this.socket.close();
console.log("全局 WebSocket 已主动关闭");
}
},
methods: {
connectWebSocket(initialDelay = 500) {
this.socket = new WebSocket(
`${webSocketUrl}`
);

this.socket.onopen = () => {
console.log('全局 WebSocket 已连接');
this.retryCount = 0;
this.startHeartbeat();
this.socket.onmessage = this.handleMessage;
};

this.socket.onclose = (e) => {
console.log('WebSocket 连接已关闭', e, new Date());
this.handleReconnect(initialDelay);
};

this.socket.onerror = (error) => {
console.error('WebSocket 错误:', error);
this.socket.close();
};
},
handleMessage(event) {
console.log('收到 WebSocket 消息:', event.data);
this.startHeartbeat();
// 处理消息逻辑
const data = JSON.parse(event.data);
if (data.accessNumber) {
this.clear();
this.$router.push(
`/home/${data.accessNumber}`
);
}
},
handleReconnect(initialDelay) {
if (this.isReconnecting && this.retryCount >= maxRetries) {
console.error('重连已禁用或达到最大次数');
this.closeHeartbeat();
return;
}

if (this.socket) {
this.socket.onclose = null; // 避免触发重连
this.socket.close();
}

this.isReconnecting = true;
this.retryCount += 1;
const delay = 2000;
console.log(`尝试重新连接(${this.retryCount}/${maxRetries}),延迟 ${delay}ms`);

setTimeout(() => {
this.connectWebSocket(initialDelay);
this.isReconnecting = false;
}, delay);
},
startHeartbeat() {
if (this.heartbeatTimer) {
this.closeHeartbeat();
}
this.heartbeatTimer = setInterval(() => {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify({ type: 'heartBeat', data: {} }));
console.log('WebSocket', '发送心跳数据...');
} else {
console.error('[WebSocket] 未连接');
}
}, heartbeatInterval);
},
closeHeartbeat() {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
},
clear() {
localStorage.clear();
sessionStorage.clear();
}
}
};
</script>