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; //心跳时间
|
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';
|
this.heartCheck();
|
if (data) { this.ws.send(data) }
|
};
|
|
this.ws.onmessage = e => {
|
if (e.data === 'pong') {
|
this.pingPong = 'pong'
|
} else {
|
this.msgCallback(JSON.parse(e.data));
|
}
|
};
|
|
this.ws.onclose = () => {
|
clearInterval(this.pingInterval);
|
clearInterval(this.pongInterval)
|
if (this.status === 'close') {
|
//console.log(‘手动关闭成功‘,new Date())
|
} else {
|
this.relink(); //非人为关闭进行重连
|
}
|
}
|
this.ws.onerror = e => {
|
console.log(e);
|
this.relink()
|
}
|
return false
|
}
|
|
heartCheck() {// 心跳
|
this.pingPong = 'ping';
|
let timer = this.time + 1000
|
this.pingInterval = setInterval(() => {
|
if (this.ws.readyState === 1) {
|
this.ws.send('ping')
|
}
|
}, this.time);
|
this.pongInterval = setInterval(() => {
|
if (this.pingPong === 'ping') {
|
clearInterval(this.pingInterval);
|
clearInterval(this.pongInterval)
|
this.ws.close()
|
} else {
|
this.pingPong = 'ping'
|
}
|
}, timer)
|
}
|
|
sendHandle(data) {
|
return this.ws.send(data);
|
}
|
|
relink() {
|
if (this.status == 'open' && this.readyState == 1) { //连接正常
|
return
|
}
|
if (this.initTimeOut) { //定时器已经启动
|
return;
|
}
|
this.initTimeOut = setTimeout(() => {
|
clearInterval(this.pingInterval);
|
clearInterval(this.pongInterval);
|
this.initTimeOut = null;
|
this.init();
|
}, this.initTime)
|
}
|
|
// 手动关闭WebSocket
|
closeMyself() {
|
console.log('执行手动关闭', new Date());
|
this.status = 'close';
|
this.ws.close();
|
this.ws = null
|
}
|
}
|