From 5f45bc98fb5be5e5f94315028256166c3d5974de Mon Sep 17 00:00:00 2001 From: GGJ <357021191@qq.com> Date: Fri, 17 Jan 2025 15:06:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20WebSocket=20=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E6=B5=8F=E8=A7=88=E5=99=A8=E5=BF=83=E8=B7=B3=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/utils/webSocketClient.ts | 28 +++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/frontend/src/utils/webSocketClient.ts b/frontend/src/utils/webSocketClient.ts index ab905e0..c613c8f 100644 --- a/frontend/src/utils/webSocketClient.ts +++ b/frontend/src/utils/webSocketClient.ts @@ -1,5 +1,9 @@ import {ElMessage} from "element-plus"; + + + + export default class SocketService { static instance = null; static get Instance() { @@ -18,7 +22,7 @@ export default class SocketService { sendRetryCount = 0; // 重新连接尝试的次数 connectRetryCount = 0; - + work:any; heartbeatTimer; heartbeatInterval = 6000; // 心跳间隔,单位毫秒 lastActivityTime= 0; // 上次活动时间戳 @@ -36,7 +40,7 @@ export default class SocketService { // 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.onopen = () => { @@ -96,12 +100,22 @@ export default class SocketService { startHeartbeat() { - this.heartbeatTimer = setInterval(() => { - if ((Date.now() - this.lastActivityTime) > this.heartbeatInterval) { + let _this = this + 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() { console.log("进入心跳消息发送。。。。。。。。。。。。。") @@ -115,7 +129,9 @@ export default class SocketService { } clearHeartbeat() { + this.work.terminate(); if (this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; }