export class WebSocketClass {
constructor(url
, msgCallback
, name
= 'default', startWsAfter
) {
this.url
= url
;
this.msgCallback
= msgCallback
;
this.name
= name
;
this.ws
= null;
this.status
= null;
this.startWsAfter
= startWsAfter
;
this.interval
= true;
}
connect(data
) {
this.ws
= new WebSocket(this.url
);
this.ws
.onopen = e
=> {
this.status
= 'open';
console
.log(`${this.name}连接成功`, e
);
return this.startWsAfter();
if (data
!== undefined
) {
return this.ws
.send(data
);
}
};
this.ws
.onmessage = e
=> {
return this.msgCallback(e
.data
);
};
this.ws
.onclose = e
=> {
this.closeHandle(e
);
};
this.ws
.onerror = e
=> {
this.closeHandle(e
);
};
}
sendHandle(data
) {
return this.ws
.send(data
);
}
throttle(fn
, interval
) {
let last
= 0;
return function (...args
) {
let context
= this;
let now
= +new Date();
if (now
- last
< interval
) return;
last
= now
;
fn
.apply(this, args
);
};
}
closeHandle(e
= 'err') {
if (this.status
!== 'close') {
console
.log(this.name
+ '网络不稳定断开进行重连');
if (!this.interval
) {
return;
}
this.interval
= false;
setTimeout(() => {
this.connect();
this.interval
= true;
}, 1000);
}
}
closeWebsocket() {
this.status
= 'close';
console
.log(`手动关闭websocket`);
return this.ws
.close();
}
heartCheck
= {
timeout
: 5000,
timeoutObj
: null,
serverTimeoutObj
: null,
reset
: function () {
clearTimeout(this.timeoutObj
);
clearTimeout(this.serverTimeoutObj
);
return this;
},
start
: function () {
var self
= this;
this.timeoutObj
&& clearTimeout(this.timeoutObj
);
this.serverTimeoutObj
&& clearTimeout(this.serverTimeoutObj
);
this.timeoutObj
= setTimeout(function () {
this.ws
.send('HeartBeat');
console
.log('ping');
self
.serverTimeoutObj
= setTimeout(function () {
this.ws
.closeWebsocket();
}, self
.timeout
);
}, this.timeout
);
},
};
}
转载请注明原文地址: https://lol.8miu.com/read-32775.html