修改 WebSocket 关闭浏览器心跳问题

This commit is contained in:
GGJ
2025-01-17 15:06:44 +08:00
parent ce47831992
commit 5f45bc98fb

View File

@@ -1,5 +1,9 @@
import {ElMessage} from "element-plus"; import {ElMessage} from "element-plus";
export default class SocketService { export default class SocketService {
static instance = null; static instance = null;
static get Instance() { static get Instance() {
@@ -18,7 +22,7 @@ export default class SocketService {
sendRetryCount = 0; sendRetryCount = 0;
// 重新连接尝试的次数 // 重新连接尝试的次数
connectRetryCount = 0; connectRetryCount = 0;
work:any;
heartbeatTimer; heartbeatTimer;
heartbeatInterval = 6000; // 心跳间隔,单位毫秒 heartbeatInterval = 6000; // 心跳间隔,单位毫秒
lastActivityTime= 0; // 上次活动时间戳 lastActivityTime= 0; // 上次活动时间戳
@@ -36,7 +40,7 @@ export default class SocketService {
// let token = '4E6EF539AAF119D82AC4C2BC84FBA21F'; // let token = '4E6EF539AAF119D82AC4C2BC84FBA21F';
const url = 'ws://localhost:7777/hello?name=cdf' const url = 'ws://192.168.1.127:7777/hello?name=cdf'
this.ws = new WebSocket(url); this.ws = new WebSocket(url);
// 连接成功的事件 // 连接成功的事件
this.ws.onopen = () => { this.ws.onopen = () => {
@@ -96,12 +100,22 @@ export default class SocketService {
startHeartbeat() { startHeartbeat() {
this.heartbeatTimer = setInterval(() => { let _this = this
if ((Date.now() - this.lastActivityTime) > this.heartbeatInterval) { var url = window.URL.createObjectURL(new Blob(['(function(e){setInterval(function(){this.postMessage(null)},3000)})()']));
this.work = new Worker(url)
this.work.onmessage = function(e){
if ((Date.now() - _this.lastActivityTime) > _this.heartbeatInterval) {
// 如果超过心跳间隔没有活动,发送心跳消息 // 如果超过心跳间隔没有活动,发送心跳消息
this.sendHeartbeat(); _this.sendHeartbeat();
} }
}, this.heartbeatInterval/2); // 每半个心跳间隔检查一次
}
// this.heartbeatTimer = setInterval(() => {
// if ((Date.now() - this.lastActivityTime) > this.heartbeatInterval) {
// // 如果超过心跳间隔没有活动,发送心跳消息
// this.sendHeartbeat();
// }
// }, this.heartbeatInterval/2); // 每半个心跳间隔检查一次
} }
sendHeartbeat() { sendHeartbeat() {
console.log("进入心跳消息发送。。。。。。。。。。。。。") console.log("进入心跳消息发送。。。。。。。。。。。。。")
@@ -115,7 +129,9 @@ export default class SocketService {
} }
clearHeartbeat() { clearHeartbeat() {
this.work.terminate();
if (this.heartbeatTimer) { if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer); clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null; this.heartbeatTimer = null;
} }