1、通过createWebSocket创建连接
function createWebSocket() {
try {
// 创建一个WebSocket实例 ws
ws = new WebSocket(wsUrl);
// ws 初始化一些事件
init();
} catch(e) {
console.log('catch');
// 连接失败后重连
reconnect(wsUrl);
}
}
2、创建init方法,初始化一些监听事件,如果希望websocket连接一直保持, 我们会在close或者error上绑定重新连接方法。
function init() {
// ws 监听onclose事件
ws.onclose = function () {
console.log('链接关闭');
// close事件触发后重连
reconnect(wsUrl);
};
ws.onerror = function() {
console.log('发生异常了');
// 连接发生异常需要重连
reconnect(wsUrl);
};
// 连接打开的时候触发
ws.onopen = function () {
// 连接打开后发送心跳
heartCheck.start();
};
// 收到服务端消息的时候触发
ws.onmessage = function (event) {
console.log('接收到消息');
//拿到任何消息都说明当前连接是正常的,然后接着继续发送心跳
heartCheck.start();
}
}
3、 重连操作,通过设置lockReconnect变量避免重复连接
var lockReconnect = false;//避免重复连接
function reconnect(url) {
if(lockReconnect) {
return;
};
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
tt && clearTimeout(tt);
tt = setTimeout(function () {
createWebSocket(url);
lockReconnect = false;
}, 4000);
}
4 心跳检测
var heartCheck = {
timeout: 3000, //每隔三秒发送心跳
severTimeout: 5000, //服务端超时时间
timeoutObj: null,
serverTimeoutObj: null,
start: function(){
var _this = this;
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
ws.send("123456789"); // 心跳包
//计算答复的超时时间
_this.serverTimeoutObj = setTimeout(function() {
// 超时后手动关闭会触发onclose事件,然后就会重连
ws.close();
}, _this.severTimeout);
}, this.timeout)
}
}