Setup websocket reconnection logic

This commit is contained in:
2025-01-01 11:21:32 -06:00
parent d2ec94f578
commit e8fe3e8ec9

View File

@@ -25,6 +25,7 @@ function useSocket(): UseSocketResult {
const [downloads, setDownloads] = useState<Download[] | null>(null);
const [executables, setExecutables] = useState<Executable[] | null>(null);
const socketRef = useRef<WebSocket | null>(null);
const allowReconnectRef = useRef<boolean>(true);
function deleteDownload(download_token: number) {
if (socketRef.current == null) {
@@ -43,6 +44,7 @@ function useSocket(): UseSocketResult {
}
useEffect(() => {
function connect() {
const socket = new WebSocket(
(window.location.protocol === "https:" ? "wss://" : "ws://") +
(import.meta.env.DEV ? "localhost:5800" : window.location.host) +
@@ -71,12 +73,27 @@ function useSocket(): UseSocketResult {
socket.onclose = (event) => {
console.log("WebSocket connection closed", event);
socketRef.current = null;
if (allowReconnectRef.current) {
setId(null);
setDownloads(null);
setExecutables(null);
setTimeout(() => {
connect();
}, 3000);
}
};
}
connect();
return () => {
// Close the socket when the component is unmounted
console.log("Unmounting, closing WebSocket connection");
socket.close();
socketRef.current?.close();
allowReconnectRef.current = false;
};
}, []);