Skip to content

Commit

Permalink
Perf: Add SFTP Heart Beat
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhaoJiSen committed Jan 6, 2025
1 parent f99fc7b commit 57f337c
Showing 1 changed file with 51 additions and 4 deletions.
55 changes: 51 additions & 4 deletions ui/src/hooks/useFileManage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);

Expand Down Expand Up @@ -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;
}
Expand Down

0 comments on commit 57f337c

Please sign in to comment.