import getWsUrl from "@/assets/js/getWsUrl";
|
|
export class WebSocketClass {
|
//ws地址
|
constructor(url, msgCallback, time, port) {
|
this.wsUrl = getWsUrl(url, port)
|
this.msgCallback = msgCallback;
|
this.time = time || 15000; //心跳时间
|
this.initTime = 5000 //重连时间
|
this.init()
|
}
|
init(data) {
|
let WSINWIN = 'WebSocket' in window
|
if (!WSINWIN) {
|
return console.log('Websocket not supported')
|
}
|
this.ws = new WebSocket(this.wsUrl);
|
this.ws.onopen = () => {
|
this.status = 'open';
|
if (data) { this.ws.send(data) }
|
};
|
|
this.ws.onmessage = e => {
|
this.msgCallback(JSON.parse(e.data));
|
};
|
|
this.ws.onclose = () => {
|
if (this.status === 'close') {
|
//console.log(‘手动关闭成功‘,new Date())
|
} else {
|
this.relink(); //非人为关闭进行重连
|
}
|
}
|
this.ws.onerror = e => {
|
console.log(e);
|
this.relink()
|
}
|
return false
|
}
|
|
sendHandle(data) {
|
return this.ws.send(data);
|
}
|
|
relink() {
|
if (this.status == 'open') { //连接正常
|
return
|
}
|
if (this.initTimeOut) { //定时器已经启动
|
return;
|
}
|
this.initTimeOut = setTimeout(() => {
|
this.initTimeOut = null;
|
this.init();
|
}, this.initTime)
|
}
|
|
// 手动关闭WebSocket
|
closeMyself() {
|
console.log('执行手动关闭', new Date());
|
this.status = 'close';
|
this.ws.close();
|
this.ws = null
|
}
|
}
|