Automatically reconnect to server (#1790)

This commit is contained in:
Matthew Tancik authored and GitHub committed 2023-04-20 18:41:31 -07:00
1 parent ee50be9de5
commit f84ad7352e
1 file changed
+17 -1
@@ -287,7 +287,7 @@ export function ViserWebSocket({ children }: { children: React.ReactNode }) {
const dispatch = useDispatch();
const store = useStore();
const ws = React.useRef<WebSocket>();
const ws = React.useRef<WebSocket | null>(null);
const websocket_url = useSelector(
(state) => state.websocketState.websocket_url,
@@ -304,8 +304,19 @@ export function ViserWebSocket({ children }: { children: React.ReactNode }) {
ws.current = new WebSocket(websocket_url);
const connecting_timeout = setTimeout(() => {
if (
ws.current != null &&
ws.current.readyState === WebSocket.CONNECTING
) {
ws.current.close();
console.log('WebSocket connection timed out');
}
}, 5000); // timeout after 5 seconds
ws.current.onopen = () => {
console.log(`Viser connected! ${websocket_url}`);
clearTimeout(connecting_timeout);
dispatch({
type: 'write',
path: 'websocketState/isConnected',
@@ -342,6 +353,11 @@ export function ViserWebSocket({ children }: { children: React.ReactNode }) {
}
}
};
// add websocket error handling
ws.current.onerror = (err) => {
console.log('Websocket error: ', err);
};
}
let timeout = setTimeout(tryConnect, 500);