import emitter from 'event-emitter'
export default class WebScoketManager {
constructor(opt) {
// 连接状态
this.opt = Object.assign({
isHeartCheck: true,
}, opt); //{link:socket地址,reConnect:是否开启重连功能,isHeartCheck:是否开启心跳检测}
this.connState = false
this.emitter = emitter()
this.initWebSocket()
this.count = 0;
this.socketEndSucc = false;
}
initWebSocket() {
// const address = (window.HIIM_SETTING.webSocketUrl||process.env.VUE_APP_WEBSOCKET_API) || ""
// if (!address) {
// return
// }
const ws = new window.WebSocket(this.opt.link) // process.env.VUE_APP_WEBSOCKET_API+'?cid=singleton'
const me = this
let _heartCheck = me.heartCheck();
ws.onopen = function (e) {
this.connState = true
me.opt.isHeartCheck && _heartCheck.reset().start(); //心跳检测重置
me.onOpen(e)
}
ws.onclose = function (e) {
me.ws = null
if (me.count < 5 && me.opt.reConnect) {
me.count++;
me.reConnection()
me.onClose(e)
me.emitter.emit('reConnect')
} else {
(!me.socketEndSucc) && me.onClose(e)
me.opt.reConnect && me.emitter.emit('endReConnect')
}
me.opt.isHeartCheck && _heartCheck.reset();
}
ws.onerror = function (e) {
me.onError(e)
}
ws.onmessage = function (e) {
me.onMessage(e)
me.opt.isHeartCheck && _heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
}
me.ws = ws
}
reConnection() {
if (!this.connState) {
this.timer = setTimeout(() => {
console.log('第' + this.count + '次重新连接websocket')
this.initWebSocket()
console.log(this.connState)
}, 5000)
}
}
onOpen(e) {
console.log('websocket已连接') //'Openened connection to websocket'
this.emitter.emit('onopen')
}
onClose(e) {
console.log('websocket已关闭', e) //'Close connection to websocket'
this.emitter.emit('onclose')
}
onMessage(e) {
// console.log(e)
let msg = e.data;
try {
msg = JSON.parse(e.data);
} catch (e) {
console.error(e)
}
this.emitter.emit('onmessage', msg, e)
}
onError(e) {
console.log('websocket出错:', e);
this.emitter.emit('onerror', e)
}
on(eventName, callback) {
this.emitter.on(eventName, callback)
}
off(eventName, callback) {
this.emitter.off(eventName, callback)
}
end() {
this.connState = true
this.ws && this.ws.close();
clearTimeout(this.timer)
console.log("关闭")
}
send(data, cb) {
this.ws.send(data);
cb && cb();
}
//心跳检测
heartCheck() {
var me = this;
return {
timeout: 1000 * 60 * 1, //1分钟发一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
var self = this;
this.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
me.send(JSON.stringify({
cmd: "13",
hbbyte: "心跳1个字节",
}));
console.log("ping!")
self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置,说明后端主动断开了
me.emitter.emit('overtime');
me.ws.close();
console.log("endiiiiiiiing");
}, self.timeout)
}, this.timeout)
}
}
}
}