websocket 的基本使用:
var ws = new WebSocket(url);
ws.onclose = function () {
//something
reconnect(); // 自定义的 websocket 重连方法
};
ws.onerror = function () {
//something
reconnect(); // 自定义的 websocket 重连方法
};
ws.onopen = function () {
//something
};
ws.onmessage = function (event) {
//something
}
想要 websocket 一直保持连接,我们在 onclose 和 onerror 方法中执行重连方法。
但是当信号不好,网络临时断开时,websocket 连接断开而不会执行 onclose 方法,这时我们就无法重连 websocket 了。
所以需要针对断网情况使用心跳重连的方式。
var heartCheck = {
timeout: 60000,//60s
timer: null,
reset: function(){ // 终止 start 的 setTimerout,不让 ws.send() 执行,然后重新执行 start
clearTimeout(this.timer);
this.start();
},
start: function(){
this.timer= setTimeout(function(){
ws.send("HeartBeat"); // send 方法执行,如果是断网状态,则会自动触发 onclose 方法,实现重连。重连方法中会执行 start 方法,再次开始心跳检测,所以这里使用的 setTimeout 而不是 setInterval
}, this.timeout)
}
}
ws.onopen = function () {
heartCheck.start(); // onopen 的时候执行 start 开始心跳检测
};
ws.onmessage = function (event) { // 接收到后端的消息执行 reset
heartCheck.reset();
}