代码:
带离开页面 刷新页面 关闭WebSocket
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
ws: null,
// WebSocket 地址
WebSocket_URL: '',
reconnectTimer: null,
reconnectTimes: 0,
// 重连最大次数
MAX_RECONNECT_TIMES: 5,
};
},
mounted() {
// 调用WebSocket
this.getalarmMarker();
},
methods: {
// 利用WebSocket 实时获取 报警数据
getalarmMarker() {
console.log('WebSocket连接测试');
this.ws = new WebSocket(this.WebSocket_URL);
this.ws.onopen = () => {
console.log('WebSocket连接成功');
clearInterval(this.reconnectTimer);
this.reconnectTimes = 0;
};
let that = this;
setInterval(function () {
// console.log('WebSocket发送信息:' + "心跳:" + new Date().toLocaleString())
that.ws.send('心跳:' + new Date().toLocaleString());
}, 60 * 1000);
this.ws.onmessage = (event) => {
console.log('接受的WebSocket参数', event);
// const dataJson = JSON.parse(event.data);
};
this.ws.onclose = (event) => {
console.log('WebSocket连接关闭', event);
if (this.reconnectTimer === null) {
console.log('正在尝试重新连接WebSocket');
this.reconnectTimer = setInterval(() => {
if (
this.MAX_RECONNECT_TIMES !== null &&
this.reconnectTimes >= this.MAX_RECONNECT_TIMES
) {
console.log(
`WebSocket连接已超过最大尝试次数(${this.MAX_RECONNECT_TIMES}),不再重试`
);
clearInterval(this.reconnectTimer);
this.reconnectTimer = null;
} else {
console.log('重新连接WebSocket');
clearInterval(this.reconnectTimer);
this.reconnectTimer = setInterval(() => {
this.getalarmMarker(1);
}, 5000);
this.reconnectTimes++;
}
}, 5000);
this.reconnectTimes++;
}
};
},
//关闭websocket
closeWebsocket(e) {
if (this.ws) {
this.ws.close();
this.ws.onclose = function (evt) {
console.log('websocket已关闭');
};
}
},
},
created() {
//绑定事件
window.addEventListener('beforeunload', (e) => this.closeWebsocket(e));
},
beforeDestroy() {
//卸载事件
window.removeEventListener('beforeunload', (e) => this.closeWebsocket(e));
},
};
</script>
<style></style>