From cd1f367b9e0f50133e2b3e15b98d5301eb9a1606 Mon Sep 17 00:00:00 2001
From: chenyao <1219716595@qq.com>
Date: Wed, 22 Apr 2026 16:08:56 +0800
Subject: [PATCH] feat:增加心跳机制

---
 src/hooks/useGlobalWS.js |   23 ++++++++++++++++++++++-
 1 files changed, 22 insertions(+), 1 deletions(-)

diff --git a/src/hooks/useGlobalWS.js b/src/hooks/useGlobalWS.js
index eee6a81..d69c771 100644
--- a/src/hooks/useGlobalWS.js
+++ b/src/hooks/useGlobalWS.js
@@ -4,6 +4,7 @@
 import useAppStore from "../store/modules/app/index.js";
 
 let socketTask = null
+let heartbeatTimer = null
 
 export function useGlobalWS() {
 	const userStore = useUserStore();
@@ -40,6 +41,7 @@
 
 	// 关闭ws
 	function closeWS() {
+    stopHeartbeat()
 		socketTask?.close({
 			success: () => {
 				console.log('ws关闭连接');
@@ -80,7 +82,7 @@
     // 监听连接关闭
     socketTask.onClose((res) => {
       console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
-
+      startHeartbeat()
       // 根据不同的关闭代码处理
       if (res.code === 1000) { // 正常关闭
         console.log('连接正常关闭')
@@ -99,6 +101,25 @@
     })
 	}
 
+  function startHeartbeat() {
+    stopHeartbeat()
+    heartbeatTimer = setInterval(() => {
+      if (socketTask && socketTask.readyState === 1) {
+        // 尝试以 JSON 格式发送,并降低频率(30秒一次)以减少服务器负担
+        socketTask.send({
+          data: JSON.stringify({ type: 'ping', timestamp: Date.now() })
+        });
+      }
+    }, 30000)
+  }
+
+  function stopHeartbeat() {
+    if (heartbeatTimer) {
+      clearInterval(heartbeatTimer)
+      heartbeatTimer = null
+    }
+  }
+
 
 	watch(access_token, initWS, {immediate: true})
 }

--
Gitblit v1.9.3