data{
lockReconnect:false,
timeout: 28 * 1000,//30秒一次心跳
timeoutObj: null,//心跳心跳倒计时
serverTimeoutObj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
},
beforeRouteLeave(to, form, next) {
this.isClose = true
this.closeWebSocket()
next()
},
created() {
window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
},
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
},
mounted() {
this.init()
},
methods: {
reconnect () { // 重新连接
if(this.lockReconnect) return;
this.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
this.timeoutnum && clearTimeout(this.timeoutnum);
this.timeoutnum = setTimeout(() => {
//新连接
this.websocket.close()
this.init();
this.$message({
message: '网络异常,正在尝试重新连接',
type: 'warning'
});
this.lockReconnect = false;
}, 5000);
},
reset () { // 重置心跳
// 清除时间
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
// 重启心跳
this.start();
},
start () { // 开启心跳
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(() => {
// 这里发送一个心跳,后端收到后,返回一个心跳消息,
if (this.websocket && this.websocket.readyState == 1) { // 如果连接正常
// 开启心跳:连接正常
this.websocketsend('heartbeat');
} else { // 否则重连
// 开启心跳:连接不正常,重连
this.reconnect();
}
}, this.timeout)
},
clear(){//连接断开,清空数据
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
},
beforeunloadFn(e) {
this.clear()
this.reconnect()
},
init(){
if ("WebSocket" in window) {
this.websocket = new WebSocket('ws://192.168.2.99:9001/websocket/'+this.id) //公司测试
// this.websocket = new WebSocket('ws://192.190.10.39:9001/websocket/'+this.id) //现场
this.initWebSocket()
} else {
alert("当前浏览器 Not support websocket");
}
},
initWebSocket() {
console.log('开始连接。。。')
// 连接错误
this.websocket.onerror = this.setErrorMessage;
// 连接成功
this.websocket.onopen = this.setOnopenMessage;
// 收到消息的回调
this.websocket.onmessage = this.setOnmessageMessage;
// 连接关闭的回调
this.websocket.onclose = this.setOncloseMessage;
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = this.onbeforeunload;
},
setErrorMessage() {
//重连
this.reconnect();
console.log(
"WebSocket连接发生错误 状态码:" + this.websocket.readyState
);
},
setOnopenMessage() {
//开启心跳
this.start();
this.$message({
message: '连接成功',
type: 'success'
});
console.log("WebSocket连接成功 状态码:" + this.websocket.readyState);
},
setOnmessageMessage(event) {
let data = JSON.parse(event.data)
},
setOncloseMessage() {
//重连
if(!this.isClose){
this.reconnect();
}
console.log("WebSocket连接关闭 状态码:" + this.websocket.readyState);
},
onbeforeunload () {
this.closeWebSocket();
},
//websocket发送消息
websocketsend(messsage) {
console.log('websocket发送消息')
this.websocket.send(messsage)
},
closeWebSocket() { // 关闭websocket
this.websocket.close()
this.clear()
},
}
WebSocket 心跳机制
最新推荐文章于 2024-07-02 08:21:06 发布