var heartCheck = {
pongTime: 30 * AP.SECOND, //30秒接收心跳
pingTime: (30 * AP.SECOND / 10) * 8,
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
// clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
PingStart: function () {
var self = this;
this.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
if (WEB_SOCKET != null && WEB_SOCKET.readyState == WebSocket.OPEN) {
console.log("心跳发送PING");
WEB_SOCKET.send("PING")
self.PingStart();
}
}, this.pingTime) //10秒发送一次心跳
},
PongStart: function () {
var self = this;
self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置,说明后端主动断开了
if (WEB_SOCKET != null) {
console.log("服务器30秒没有响应,关闭连接")
WEB_SOCKET.close();
}
}, self.pongTime)
}
}
WEB_SOCKET = new WebSocket("ws://88.gaoqiaoxue.com/v5/apipost.io?userToken=" + AP.USER.userIndendify);
WEB_SOCKET.onopen = function (evt) {
console.log("连接成功,发送ping");
WEB_SOCKET.send("PING")
heartCheck.PingStart();
heartCheck.reset().PongStart(); //打开心跳检测
};
WEB_SOCKET.onerror = function (err) {
console.log(err);
if (WEB_SOCKET != null) {
console.log("异常,关闭连接", err);
WEB_SOCKET.close();
}
reject(err)
}
WEB_SOCKET.onmessage = function (evt) {
if (WEB_SOCKET != null) {
heartCheck.reset().PongStart(); //拿到任何消息都说明当前连接是正常的 心跳检测重置
}
};
WEB_SOCKET.onclose = function (evt) {
console.log("Connection closed.");
};
//自动重连机制 也和这个差不多,后面在发出来