class WebsocketConn {
constructor(url, cb) {
this.cb = cb;
this.url = url
this.ws = null;
this.s=0 //检测错误重新连接次数
this.isnor=true
this.lockReconnect = false; //避免ws重复连接
this.timeout = 30000; // 心跳检测时间
this.heartCheckTimer = null // 心跳检测定时器
this.heartCheckServerTimer = null;
this.timetag=null
}
heartCheckToReset() {
clearTimeout(this.heartCheckTimer);
clearTimeout(this.heartCheckServerTimer);
return this;
}
heartCheckToStart() {
this.heartCheckTimer && clearTimeout(this.heartCheckTimer);
this.heartCheckServerTimer && clearTimeout(this.heartCheckServerTimer);
this.heartCheckTimer = setTimeout(() => {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage 拿到返回的心跳就说明连接正常
this.ws.send("天王盖地虎");
console.log("天王盖地虎")
this.heartCheckServerTimer = setTimeout(() => {//如果超过一定时间还没重置,说明后端主动断开了
this.isnor=false
this.ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, this.timeout)
}, this.timeout)
}
create() {
console.log(this.url)
try{
if('WebSocket' in window){
this.ws = new WebSocket(this.url);
console.log(this.ws)
}
this.initEventHandle();
}catch(e){
this.reconnect(this.url);
console.log(e);
}
}
initEventHandle() {
console.log(this.cb)
const _this=this
this.ws.onclose = () => {
!this.isnor && this.reconnect(this.url);
console.log("websocket 连接关闭!"+ new Date().toLocaleString());
};
this.ws.onerror = (error) => {
this.s++
if(this.s<6){
this.reconnect(this.url);
this.isnor=false
}else{
this.isnor=true
this.s=0
}
console.log("websocket 连接错误!"+this.s);
};
this.ws.onopen = () => {
this.heartCheckToReset().heartCheckToStart(); //心跳检测重置
this.s=0
console.log("websocket 连接成功!"+new Date().toLocaleString());
};
this.ws.onmessage = (event) => { //如果获取到消息,心跳检测重置
this.s=0
console.log(event)
_this.cb(event)
if (event.data === '宝塔镇河妖') { //获取到的后端发送的心跳检测
this.heartCheckToReset().heartCheckToStart();
return
}
// this.heartCheckToReset().heartCheckToStart(); //拿到任何消息都说明当前连接是正常的
// this.cb();
console.log(event)
console.log("websocket 收到消息啦:" + event);
};
}
reconnect() {
console.log("重新连接")
if(this.lockReconnect) return;
this.lockReconnect = true;
this.timetag && clearTimeout(this.timetag)
this.timetag=setTimeout(() => { //重连,设置延迟避免请求过多
this.create(this.url);
this.lockReconnect = false;
}, 2000);
}
close() {
this.ws.close();
}
}
export default WebsocketConn
/**
* 使用 this.websocket = new this.$webscoket(_wsurl, _getMessage);
this.websocket.create()
销毁this.websocket.close();
*/