From 964db2dfce990fe920f014c62a0894bef8bbee11 Mon Sep 17 00:00:00 2001
From: 疯狂的狮子Li <15040126243@163.com>
Date: 星期一, 29 七月 2024 15:02:41 +0800
Subject: [PATCH] update 优化 使用 vueuse 重构 websocket 实现

---
 src/utils/websocket.ts |  148 +++++++++++++------------------------------------
 1 files changed, 40 insertions(+), 108 deletions(-)

diff --git a/src/utils/websocket.ts b/src/utils/websocket.ts
index d4dd8a8..37942d8 100644
--- a/src/utils/websocket.ts
+++ b/src/utils/websocket.ts
@@ -22,118 +22,50 @@
 import { ElNotification } from 'element-plus';
 import useNoticeStore from '@/store/modules/notice';
 
-let socketUrl: any = ''; // socket鍦板潃
-let websocket: any = null; // websocket 瀹炰緥
-let heartTime: any = null; // 蹇冭烦瀹氭椂鍣ㄥ疄渚�
-let socketHeart = 0 as number; // 蹇冭烦娆℃暟
-const HeartTimeOut = 10000; // 蹇冭烦瓒呮椂鏃堕棿 10000 = 10s
-let socketError = 0 as number; // 閿欒娆℃暟
-
 // 鍒濆鍖杝ocket
 export const initWebSocket = (url: any) => {
   if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
     return;
   }
-  socketUrl = url;
-  // 鍒濆鍖� websocket
-  websocket = new WebSocket(url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID);
-  websocketonopen();
-  websocketonmessage();
-  websocketonerror();
-  websocketclose();
-  sendSocketHeart();
-  return websocket;
-};
-
-// socket 杩炴帴鎴愬姛
-export const websocketonopen = () => {
-  websocket.onopen = function () {
-    console.log('杩炴帴 websocket 鎴愬姛');
-    resetHeart();
-  };
-};
-
-// socket 杩炴帴澶辫触
-export const websocketonerror = () => {
-  websocket.onerror = function (e: any) {
-    console.log('杩炴帴 websocket 澶辫触', e);
-  };
-};
-
-// socket 鏂紑閾炬帴
-export const websocketclose = () => {
-  websocket.onclose = function (e: any) {
-    console.log('鏂紑杩炴帴', e);
-  };
-};
-
-// socket 閲嶇疆蹇冭烦
-export const resetHeart = () => {
-  socketHeart = 0;
-  socketError = 0;
-  clearInterval(heartTime);
-  sendSocketHeart();
-};
-
-// socket蹇冭烦鍙戦��
-export const sendSocketHeart = () => {
-  heartTime = setInterval(() => {
-    // 濡傛灉杩炴帴姝e父鍒欏彂閫佸績璺�
-    if (websocket.readyState == 1) {
-      // if (socketHeart <= 30) {
-      websocket.send(
-        JSON.stringify({
-          type: 'ping'
-        })
-      );
-      socketHeart = socketHeart + 1;
-    } else {
-      // 閲嶈繛
-      reconnect();
+  url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID
+  useWebSocket(url, {
+    autoReconnect: {
+      // 閲嶈繛鏈�澶ф鏁�
+      retries: 3,
+      // 閲嶈繛闂撮殧
+      delay: 1000,
+      onFailed() {
+        console.log('websocket閲嶈繛澶辫触');
+      },
+    },
+    heartbeat: {
+      message: JSON.stringify({type: 'ping'}),
+      // 鍙戦�佸績璺崇殑闂撮殧
+      interval: 10000,
+      // 鎺ユ敹鍒板績璺硆esponse鐨勮秴鏃舵椂闂�
+      pongTimeout: 2000,
+    },
+    onConnected() {
+      console.log('websocket宸茬粡杩炴帴');
+    },
+    onDisconnected() {
+      console.log('websocket宸茬粡鏂紑');
+    },
+    onMessage: (_, e) => {
+      if (e.data.indexOf('ping') > 0) {
+        return;
+      }
+      useNoticeStore().addNotice({
+        message: e.data,
+        read: false,
+        time: new Date().toLocaleString()
+      });
+      ElNotification({
+        title: '娑堟伅',
+        message: e.data,
+        type: 'success',
+        duration: 3000
+      });
     }
-  }, HeartTimeOut);
-};
-
-// socket閲嶈繛
-export const reconnect = () => {
-  if (socketError <= 2) {
-    clearInterval(heartTime);
-    initWebSocket(socketUrl);
-    socketError = socketError + 1;
-    // eslint-disable-next-line prettier/prettier
-    console.log('socket閲嶈繛', socketError);
-  } else {
-    // eslint-disable-next-line prettier/prettier
-    console.log('閲嶈瘯娆℃暟宸茬敤瀹�');
-    clearInterval(heartTime);
-  }
-};
-
-// socket 鍙戦�佹暟鎹�
-export const sendMsg = (data: any) => {
-  websocket.send(data);
-};
-
-// socket 鎺ユ敹鏁版嵁
-export const websocketonmessage = () => {
-  websocket.onmessage = function (e: any) {
-    if (e.data.indexOf('heartbeat') > 0) {
-      resetHeart();
-    }
-    if (e.data.indexOf('ping') > 0) {
-      return;
-    }
-    useNoticeStore().addNotice({
-      message: e.data,
-      read: false,
-      time: new Date().toLocaleString()
-    });
-    ElNotification({
-      title: '娑堟伅',
-      message: e.data,
-      type: 'success',
-      duration: 3000
-    });
-    return e.data;
-  };
+  });
 };

--
Gitblit v1.9.3