websocket功能优化

pull/170/head^2
zhangdaiscott 2022-09-22 14:05:16 +08:00
parent 5f5207b4aa
commit ef65bb830e
1 changed files with 27 additions and 38 deletions

View File

@ -1,17 +1,10 @@
// noinspection JSUnusedGlobalSymbols // noinspection JSUnusedGlobalSymbols
import { computed, reactive, ref, unref } from 'vue'; import { unref } from 'vue';
import { useWebSocket as $useWebSocket, WebSocketResult } from '@vueuse/core'; import { useWebSocket, WebSocketResult } from '@vueuse/core';
import { getToken } from '/@/utils/auth'; import { getToken } from '/@/utils/auth';
const state = reactive({ let result: WebSocketResult<any>;
server: '',
sendValue: '',
recordList: [] as { id: number; time: number; res: string }[],
});
const result = ref<WebSocketResult<any>>();
const listeners = new Map(); const listeners = new Map();
/** /**
@ -19,25 +12,28 @@ const listeners = new Map();
* @param url * @param url
*/ */
export function connectWebSocket(url: string) { export function connectWebSocket(url: string) {
if (!unref(getIsOpen)) { //update-begin-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端,存在性能和安全问题。 #3278
state.server = url; let token = (getToken() || '') as string;
//update-begin-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端,存在性能和安全问题。 #3278 result = useWebSocket(url, {
let token = (getToken() || '') as string; // 自动重连 (遇到错误最多重复连接10次)
result.value = $useWebSocket(state.server, { autoReconnect: {
// 自动重连 retries : 10,
autoReconnect: true, delay : 5000
// 心跳检测 },
heartbeat: false, // 心跳检测
protocols: [token], heartbeat: {
}); message: "ping",
//update-end-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端,存在性能和安全问题。 #3278 interval: 55000
},
//【jeecgboot-vue3/issues/I5KULW】Websocket 连接后自动给关闭 protocols: [token],
//result.value.open(); });
const ws = unref(result.value.ws); //update-end-author:taoyan date:2022-4-24 for: v2.4.6 的 websocket 服务端,存在性能和安全问题。 #3278
if (ws) { if (result) {
ws.onopen = onOpen; result.open = onOpen;
ws.onclose = onClose; result.close = onClose;
const ws = unref(result.ws);
if(ws!=null){
ws.onerror = onError; ws.onerror = onError;
ws.onmessage = onMessage; ws.onmessage = onMessage;
} }
@ -57,9 +53,6 @@ function onError(e) {
} }
function onMessage(e) { function onMessage(e) {
if (e.data === 'ping') {
return;
}
console.debug('[WebSocket] -----接收消息-------', e.data); console.debug('[WebSocket] -----接收消息-------', e.data);
try { try {
const data = JSON.parse(e.data); const data = JSON.parse(e.data);
@ -75,10 +68,6 @@ function onMessage(e) {
} }
} }
/**
* WebSocket
*/
export const getIsOpen = computed(() => result.value?.status.value === 'OPEN');
/** /**
* WebSocket * WebSocket
@ -103,6 +92,6 @@ export function offWebSocket(callback: (data: object) => any) {
listeners.delete(callback); listeners.delete(callback);
} }
export function useWebSocket() { export function useMyWebSocket() {
return unref(result); return result;
} }