Browse Source

socket总断,换一个写法

pull/7021/head
JEECG 4 months ago
parent
commit
d0f09480ca
  1. 70
      jeecgboot-vue3/src/hooks/web/useWebSocket.ts

70
jeecgboot-vue3/src/hooks/web/useWebSocket.ts

@ -13,35 +13,69 @@ const listeners = new Map();
*/ */
export function connectWebSocket(url: string) { export function connectWebSocket(url: string) {
//update-begin-author:taoyan date:2022-4-24 for: v2.4.6 websocket #3278 //update-begin-author:taoyan date:2022-4-24 for: v2.4.6 websocket #3278
let token = (getToken() || '') as string; const token = (getToken() || '') as string;
result = useWebSocket(url, { result = useWebSocket(url, {
// (10) // (10)
autoReconnect: { autoReconnect: {
retries : 10, retries: 10,
delay : 5000 delay: 5000,
}, },
// //
heartbeat: { heartbeat: {
message: "ping", message: 'ping',
interval: 55000 // 55
interval: 5000,
}, },
protocols: [token], protocols: [token],
// update-begin--author:liaozhiyang---date:20240726---for[issues/6662] socket
onConnected: function (ws) {
console.log('[WebSocket] 连接成功', ws);
},
onDisconnected: function (ws, event) {
console.log('[WebSocket] 连接断开:', ws, event);
},
onError: function (ws, event) {
console.log('[WebSocket] 连接发生错误: ', ws, event);
},
onMessage: function (_ws, e) {
console.debug('[WebSocket] -----接收消息-------', e.data);
try {
//update-begin---author:wangshuai---date:2024-05-07---for:issues/1161websocket---
if (e.data === 'ping') {
return;
}
//update-end---author:wangshuai---date:2024-05-07---for:issues/1161websocket---
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);
}
},
// update-end--author:liaozhiyang---date:20240726---for[issues/6662] socket
}); });
// update-begin--author:liaozhiyang---date:20240726---for[issues/6662] socket
//update-end-author:taoyan date:2022-4-24 for: v2.4.6 websocket #3278 //update-end-author:taoyan date:2022-4-24 for: v2.4.6 websocket #3278
if (result) { // if (result) {
result.open = onOpen; // result.open = onOpen;
result.close = onClose; // result.close = onClose;
const ws = unref(result.ws); // const ws = unref(result.ws);
if(ws!=null){ // if(ws!=null){
ws.onerror = onError; // ws.onerror = onError;
ws.onmessage = onMessage; // ws.onmessage = onMessage;
//update-begin---author:wangshuai---date:2024-04-30---for:issues/1217--- // //update-begin---author:wangshuai---date:2024-04-30---for:issues/1217---
ws.onopen = onOpen; // ws.onopen = onOpen;
ws.onclose = onClose; // ws.onclose = onClose;
//update-end---author:wangshuai---date:2024-04-30---for:issues/1217--- // //update-end---author:wangshuai---date:2024-04-30---for:issues/1217---
} // }
} // }
// update-end--author:liaozhiyang---date:20240726---for[issues/6662] socket
} }
function onOpen() { function onOpen() {

Loading…
Cancel
Save