mirror of
https://github.com/Xevion/dynamic-preauth.git
synced 2025-12-05 23:14:53 -06:00
Setup websocket reconnection logic
This commit is contained in:
@@ -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;
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user