罗广辉
2026-04-24 648904d076ae6e17892b40675598b1c8dc474277
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import {useUserStore} from "@/store/index.js";
import {getEnvObj} from "@/utils/index.js";
import useAppStore from "../store/modules/app/index.js";
 
let socketTask = null
let heartbeatTimer = null
 
export function useGlobalWS() {
    const userStore = useUserStore();
  const appStore = useAppStore();
 
    const userId = computed(() => userStore?.userInfo?.user_id)
    const access_token = computed(() => userStore?.userInfo?.access_token)
    const {VITE_APP_WS_API_URL} = getEnvObj()
 
    // 消息处理
    function messageHandler(payload) {
        switch (payload.biz_code) {
            case 'JOB_ISREFRESH':
        appStore.setJobUpdateKeyAdd()
                break
            case 'DEVICE_ISREFRESH':
        appStore.setDeviceUpdateKeyAdd()
                break
            case 'DOWNLOAD_PROGRESS':
                break
            case 'LOGOUT_USER':
                userStore.setUserInfo(null)
                uni.reLaunch({
                    url: '/pages/login/index'
                })
                break
            default:
                break;
        }
    }
 
    // 关闭ws
    function closeWS() {
    stopHeartbeat()
        socketTask?.close({
            success: () => {
                console.log('ws关闭连接');
            },
        })
    }
 
    // 初始化ws
    function initWS() {
        // 关闭,再连接ws
        closeWS()
        if (!access_token.value) return
        const url = VITE_APP_WS_API_URL
            + `?x-auth-token=${encodeURI(access_token?.value)}`
            + `&model_type=3&workspace-id=${userId.value}`
        // 创建连接
        socketTask = uni.connectSocket({
            url: url,
            success: () => {
                console.log('ws连接成功');
            },
            fail: (err) => {
                console.error('ws连接失败:', err);
            }
        });
        // 消息监听
        socketTask.onMessage((result) => {
            messageHandler(JSON.parse(result.data))
        })
    //==================================
    // 监听连接打开
    socketTask.onOpen((res) => {
      console.log('✅ WebSocket连接已建立')
      // reconnectAttempts = 0 // 连接成功后重置重连次数
      // 可以在这里发送心跳或订阅消息
      // startHeartbeat()
    })
    // 监听连接关闭
    socketTask.onClose((res) => {
      console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
      startHeartbeat()
      // 根据不同的关闭代码处理
      if (res.code === 1000) { // 正常关闭
        console.log('连接正常关闭')
      } else if (res.code === 1006) { // 异常关闭
        console.log('连接异常关闭,尝试重连...')
      } else if (res.code === 1011) { // 服务器内部错误
        console.log('服务器内部错误(1011),延迟重连...')
      } else {
        console.log('其他原因关闭,尝试重连...')
      }
    })
 
    // 监听错误
    socketTask.onError((err) => {
      console.error('WebSocket发生错误:', err)
    })
    }
 
  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})
}