data() {
return {
wsurl: 'ws://127.0.0.1:8080',
websock: null,
lockReconnect: false,
timerReconnect: null,
heartTimeout: null,
serverTimeout: null
};
},
created() {
this.createWebSocket();
},
beforeDestroy() {
if (this.websock) this.websock.close();
},
createWebSocket() {
try {
this.websock = new WebSocket(this.wsurl);
this.initWebSocket();
} catch (e) {
console.log('catch', e);
this.reconnect();
}
},
initWebSocket() {
this.websock.onmessage = (e) => {
console.log('数据接收', e);
if (e.data === 'pong') {
this.heartCheck();
}
};
this.websock.onopen = () => {
console.log('连接成功', this.websock);
this.heartCheck();
};
this.websock.onerror = () => {
console.log('连接失败');
this.reconnect();
};
this.websock.onclose = (e) => {
console.log('断开连接', e);
this.reconnect();
};
},
reconnect() {
if (this.lockReconnect) {
return;
}
console.log('发起重连');
this.lockReconnect = true;
this.timerReconnect && clearTimeout(this.timerReconnect);
this.timerReconnect = setTimeout(() => {
this.createWebSocket();
this.lockReconnect = false;
}, 3 * 1000);
},
heartCheck() {
this.heartTimeout && clearTimeout(this.heartTimeout);
this.serverTimeout && clearTimeout(this.serverTimeout);
this.heartTimeout = setTimeout(() => {
console.log('发送ping');
this.websock.send('ping');
this.serverTimeout = setTimeout(() => {
this.websock.close();
console.log('答复超时');
}, 5 * 1000);
}, 4 * 1000);
}