2023-03-16 17:03:00 +08:00
|
|
|
import { useRef } from "react";
|
2024-01-14 17:30:18 +08:00
|
|
|
import WebSocket from "tauri-plugin-websocket-api";
|
|
|
|
|
export type WsMsgFn = (event: string) => void;
|
2023-03-16 17:03:00 +08:00
|
|
|
|
2023-08-05 17:21:15 +08:00
|
|
|
export interface WsOptions {
|
2023-03-16 17:03:00 +08:00
|
|
|
errorCount?: number; // default is 5
|
2024-01-14 17:30:18 +08:00
|
|
|
onError?: (e: any) => void;
|
2023-03-16 17:03:00 +08:00
|
|
|
}
|
|
|
|
|
|
2023-08-05 17:21:15 +08:00
|
|
|
export const useWebsocket = (onMessage: WsMsgFn, options?: WsOptions) => {
|
2023-03-16 17:03:00 +08:00
|
|
|
const wsRef = useRef<WebSocket | null>(null);
|
|
|
|
|
const timerRef = useRef<any>(null);
|
|
|
|
|
|
2024-01-14 17:30:18 +08:00
|
|
|
const disconnect = async () => {
|
2023-03-16 17:03:00 +08:00
|
|
|
if (wsRef.current) {
|
2024-01-14 17:30:18 +08:00
|
|
|
await wsRef.current.disconnect();
|
2023-03-16 17:03:00 +08:00
|
|
|
wsRef.current = null;
|
|
|
|
|
}
|
|
|
|
|
if (timerRef.current) {
|
|
|
|
|
clearTimeout(timerRef.current);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2024-01-14 17:30:18 +08:00
|
|
|
const connect = async (url: string) => {
|
2023-03-16 17:03:00 +08:00
|
|
|
let errorCount = options?.errorCount ?? 5;
|
|
|
|
|
if (!url) return;
|
2024-01-14 17:30:18 +08:00
|
|
|
const connectHelper = async () => {
|
|
|
|
|
await disconnect();
|
|
|
|
|
const ws = await WebSocket.connect(url);
|
|
|
|
|
|
|
|
|
|
ws.addListener((event) => {
|
|
|
|
|
switch (event.type) {
|
|
|
|
|
case "Text": {
|
|
|
|
|
onMessage(event.data);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
default: {
|
|
|
|
|
break;
|
|
|
|
|
}
|
2023-03-16 17:03:00 +08:00
|
|
|
}
|
|
|
|
|
});
|
2024-01-14 17:30:18 +08:00
|
|
|
wsRef.current = ws;
|
2023-03-16 17:03:00 +08:00
|
|
|
};
|
2024-01-14 17:30:18 +08:00
|
|
|
try {
|
|
|
|
|
await connectHelper();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
errorCount -= 1;
|
|
|
|
|
if (errorCount >= 0) {
|
|
|
|
|
timerRef.current = setTimeout(connectHelper, 2500);
|
|
|
|
|
} else {
|
|
|
|
|
await disconnect();
|
|
|
|
|
options?.onError?.(e);
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-03-16 17:03:00 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return { connect, disconnect };
|
|
|
|
|
};
|