dbsd_kczx/src/hooks/web/useWebSocket.ts

98 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-10 09:47:29 +08:00
// noinspection JSUnusedGlobalSymbols
2022-09-22 14:05:16 +08:00
import { unref } from 'vue';
import { useWebSocket, WebSocketResult } from '@vueuse/core';
import { getToken } from '/@/utils/auth';
2022-03-10 09:47:29 +08:00
2022-09-22 14:05:16 +08:00
let result: WebSocketResult<any>;
2022-06-10 10:44:44 +08:00
const listeners = new Map();
2022-03-10 09:47:29 +08:00
/**
* WebSocket
* @param url
*/
export function connectWebSocket(url: string) {
2022-09-22 14:05:16 +08:00
//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){
2022-06-10 10:44:44 +08:00
ws.onerror = onError;
ws.onmessage = onMessage;
2022-03-10 09:47:29 +08:00
}
}
}
function onOpen() {
2022-06-10 10:44:44 +08:00
console.log('[WebSocket] 连接成功');
2022-03-10 09:47:29 +08:00
}
function onClose(e) {
2022-06-10 10:44:44 +08:00
console.log('[WebSocket] 连接断开:', e);
2022-03-10 09:47:29 +08:00
}
function onError(e) {
2022-06-10 10:44:44 +08:00
console.log('[WebSocket] 连接发生错误: ', e);
2022-03-10 09:47:29 +08:00
}
function onMessage(e) {
2022-06-10 10:44:44 +08:00
console.debug('[WebSocket] -----接收消息-------', e.data);
2022-03-10 09:47:29 +08:00
try {
2022-06-10 10:44:44 +08:00
const data = JSON.parse(e.data);
2022-03-10 09:47:29 +08:00
for (const callback of listeners.keys()) {
try {
2022-06-10 10:44:44 +08:00
callback(data);
2022-03-10 09:47:29 +08:00
} catch (err) {
2022-06-10 10:44:44 +08:00
console.error(err);
2022-03-10 09:47:29 +08:00
}
}
} catch (err) {
2022-06-10 10:44:44 +08:00
console.error('[WebSocket] data解析失败', err);
2022-03-10 09:47:29 +08:00
}
}
/**
* WebSocket
* @param callback
*/
export function onWebSocket(callback: (data: object) => any) {
if (!listeners.has(callback)) {
if (typeof callback === 'function') {
2022-06-10 10:44:44 +08:00
listeners.set(callback, null);
2022-03-10 09:47:29 +08:00
} else {
2022-06-10 10:44:44 +08:00
console.debug('[WebSocket] 添加 WebSocket 消息监听失败:传入的参数不是一个方法');
2022-03-10 09:47:29 +08:00
}
}
}
/**
* WebSocket
*
* @param callback
*/
export function offWebSocket(callback: (data: object) => any) {
2022-06-10 10:44:44 +08:00
listeners.delete(callback);
2022-03-10 09:47:29 +08:00
}
2022-09-22 14:05:16 +08:00
export function useMyWebSocket() {
return result;
2022-03-10 09:47:29 +08:00
}