var socket;
var lockReconnect = false; //避免socket重复连接
var url = 'wss://...'; //websocket连接地址
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {//判断当前设备是否支持websocket
socket = new WebSocket(url);
socket.onclose = function (event) {
reconnect(url); //尝试重新连接
console.log(event);
console.log('连接关闭')
};
socket.onerror = function () {
reconnect(url); //尝试重新连接
console.log(event);
console.log('连接错误')
};
socket.onopen = function (event) {
heartCheck.reset().start(); //心跳检测重置
console.log(event);
console.log('连接开启')
};
socket.onmessage = function (event) {
heartCheck.reset().start(); //心跳检测重置
console.log(event);
console.log('消息接收到了,只要有接收到消息,连接都是正常的')
if (event.data != 'Msg') {
let data = JSON.parse(event.data);
}
};
} else {
alert.log("你的浏览器不支持WebSocket!");
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
socket.close();
}
// 重新连接
function reconnect(url) {
if (lockReconnect) return;
lockReconnect = true;
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
socket = new WebSocket(url);
lockReconnect = false;
}, 2000);
}
//心跳检测
var heartCheck = {
timeout: 55000, //1分钟发一次心跳,时间设置小一点较好(50-60秒之间)
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearInterval(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
var self = this;
this.timeoutObj = setInterval(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
socket.send("Msg");
self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置,说明后端主动断开了
socket.close(); //如果onclose会执行reconnect,我们执行socket.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}
|