Websocket 相关

心跳包 - 断线重连
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
// 避免重复连接
let lockReconnect = false;
let ws = null;
let wsUrl = '192.168.50.37:8181';
createWebSocket(wsUrl);

// 建立websocket连接
function createWebSocket() {
try {
ws = new WebSocket('ws://' + wsUrl);
initEventHandle();
} catch (e) {
reconnect(wsUrl);
}
}

// 重连
function reconnect() {
if (lockReconnect) {
return;
}

lockReconnect = true;
setTimeout(function () {
createWebSocket(wsUrl);
console.log('正在重连,当前时间:' + new Date());
lockReconnect = false;
}, 3000);
}

// 初始化
function initEventHandle() {
// 连接成功后
ws.onopen = function() {
console.log('连接成功');

// 心跳检测重置
heartCheck.reset();
};

// 收到消息后
ws.onmessage = function(e) {
// 心跳检测重置
heartCheck.reset();

let data = JSON.parse(e.data);
switch (data.req_type) {
case 'beat':
console.log('心跳检测成功,当前时间:' + new Date());
break;
case 'login':
console.log('SERVER:' + data.body.time);
break;
default:
break;
}
};

// 连接关闭后
ws.onclose = function() {
console.log('关闭连接');
reconnect(wsUrl);
};

ws.onerror = function () {
reconnect();
};
}

// 心跳检测
let heartCheck = {
timeout: 15000,
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
this.start();
},
start: function(){
let self = this;
this.timeoutObj = setTimeout(function(){
let heartData = {
req_type: 'beat',
req_id: new Date().getTime(),
body: [],
};

ws.send(JSON.stringify(heartData));
// 发送心跳包
console.log('发送心跳包,当前时间:' + new Date());

// 如果超过一定时间还没重置,说明后端主动断开了
self.serverTimeoutObj = setTimeout(function() {
ws.close();
}, self.timeout);
}, this.timeout)
}
};

参考资料

初探和实现websocket心跳重连(npm: websocket-heartbeat-js)

0%