From 57f337cd6eb96cc49244f5e4905a1b65cc6755af Mon Sep 17 00:00:00 2001 From: zhaojisen <1301338853@qq.com> Date: Mon, 6 Jan 2025 15:35:25 +0800 Subject: [PATCH] Perf: Add SFTP Heart Beat --- ui/src/hooks/useFileManage.ts | 55 ++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/ui/src/hooks/useFileManage.ts b/ui/src/hooks/useFileManage.ts index cbd4e8f6..c7b32da5 100644 --- a/ui/src/hooks/useFileManage.ts +++ b/ui/src/hooks/useFileManage.ts @@ -135,6 +135,39 @@ const handleSocketSftpData = (messageData: IFileManageSftpFileItem[]) => { fileManageStore.setFileList(messageData); }; +/** + * @description 心跳检测机制 + * @param socket WebSocket实例 + */ +const heartBeat = (socket: WebSocket) => { + let pingInterval: number | null = null; + + const sendPing = () => { + if (socket.CLOSED === socket.readyState || socket.CLOSING === socket.readyState) { + clearInterval(pingInterval!); + return; + } + + const pingMessage = { + id: uuid(), + type: MessageType.PING, + data: 'ping' + }; + + socket.send(JSON.stringify(pingMessage)); + }; + + sendPing(); + + pingInterval = window.setInterval(sendPing, 2000); + + return () => { + if (pingInterval) { + clearInterval(pingInterval); + } + }; +}; + /** * @description 处理 message * @param socket @@ -144,13 +177,14 @@ const initSocketEvent = (socket: WebSocket) => { const fileManageStore = useFileManageStore(); let receivedBuffers: any = []; + let clearHeartbeat: (() => void) | null = null; socket.binaryType = 'arraybuffer'; - socket.onopen = () => {}; - socket.onerror = () => {}; - - socket.onclose = () => {}; + socket.onopen = () => { clearHeartbeat = heartBeat(socket) }; + socket.onerror = () => { clearHeartbeat?.() }; + socket.onclose = () => { clearHeartbeat?.() }; + socket.onmessage = (event: MessageEvent) => { const message: IFileManage = JSON.parse(event.data); @@ -238,6 +272,19 @@ const initSocketEvent = (socket: WebSocket) => { break; } + case MessageType.PING: { + socket.send(JSON.stringify({ + id: uuid(), + type: MessageType.PONG, + data: 'pong' + })); + break; + } + + case MessageType.PONG: { + break; + } + default: { break; }