干燥机配套车间生产管理系统/云平台服务端
baoshiwei
2023-03-10 1fb197352b6a263646e4ccd3ed1c7854ede031dd
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
// noinspection JSUnusedGlobalSymbols
 
import { unref } from 'vue';
import { useWebSocket, WebSocketResult } from '@vueuse/core';
import { getToken } from '/@/utils/auth';
 
let result: WebSocketResult<any>;
const listeners = new Map();
 
/**
 * 开启 WebSocket 链接,全局只需执行一次
 * @param url
 */
export function connectWebSocket(url: string) {
  //update-begin-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端,存在性能和安全问题。 #3278
  let token = (getToken() || '') as string;
  result = useWebSocket(url, {
    // 自动重连 (遇到错误最多重复连接10次)
    autoReconnect: {
      retries : 10,
      delay : 5000
    },
    // 心跳检测
    heartbeat: {
      message: "ping",
      interval: 55000
    },
    protocols: [token],
  });
  //update-end-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端,存在性能和安全问题。 #3278
  if (result) {
    result.open = onOpen;
    result.close = onClose;
 
    const ws = unref(result.ws);
    if(ws!=null){
      ws.onerror = onError;
      ws.onmessage = onMessage;
    }
  }
}
 
function onOpen() {
  console.log('[WebSocket] 连接成功');
}
 
function onClose(e) {
  console.log('[WebSocket] 连接断开:', e);
}
 
function onError(e) {
  console.log('[WebSocket] 连接发生错误: ', e);
}
 
function onMessage(e) {
  console.debug('[WebSocket] -----接收消息-------', e.data);
  try {
    const data = JSON.parse(e.data);
    for (const callback of listeners.keys()) {
      try {
        callback(data);
      } catch (err) {
        console.error(err);
      }
    }
  } catch (err) {
    console.error('[WebSocket] data解析失败:', err);
  }
}
 
 
/**
 * 添加 WebSocket 消息监听
 * @param callback
 */
export function onWebSocket(callback: (data: object) => any) {
  if (!listeners.has(callback)) {
    if (typeof callback === 'function') {
      listeners.set(callback, null);
    } else {
      console.debug('[WebSocket] 添加 WebSocket 消息监听失败:传入的参数不是一个方法');
    }
  }
}
 
/**
 * 解除 WebSocket 消息监听
 *
 * @param callback
 */
export function offWebSocket(callback: (data: object) => any) {
  listeners.delete(callback);
}
 
export function useMyWebSocket() {
  return result;
}