From 25b03d501cd0d82075178cb8796274e44cde156a Mon Sep 17 00:00:00 2001 From: riqo Date: Tue, 8 Jun 2021 07:57:57 -0500 Subject: [PATCH] add websocket ping connection check --- src/background/ipc/account.ts | 2 +- src/background/websockets.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/background/ipc/account.ts b/src/background/ipc/account.ts index 5898509..4bf6411 100644 --- a/src/background/ipc/account.ts +++ b/src/background/ipc/account.ts @@ -42,7 +42,7 @@ const onProfile = async ( resolve(parsed.profile); } catch(e) { - reject(new Error('Failed to fetch profile.')); + reject(new Error('Unable to authenticate and fetch account profile.')); } }) ) diff --git a/src/background/websockets.ts b/src/background/websockets.ts index 70eb7ff..dec0203 100644 --- a/src/background/websockets.ts +++ b/src/background/websockets.ts @@ -3,11 +3,17 @@ import WebSocket from 'ws'; import { getAuthPayload } from "./authPayload"; +import { ipcEmit } from './helpers'; let socket: WebSocket; const socketUrl = "ws://127.0.0.1:8760" +const _connectionCheckTimeout = 4000; +const _reconnectTimeout = 1000; +let _connectionCheckInterval: ReturnType; + + // Run every time we want to connect to backend. export default function useWebSockets( receiveCallback: (s: string) => void, @@ -45,6 +51,20 @@ export default function useWebSockets( console.log("WS:Connected to WS Server!"); const jwt = getAuthPayload(); socket.send(JSON.stringify(jwt)); + + // ping server + _connectionCheckInterval = setInterval(() => { + + if (socket) socket.ping(null, true, (e: Error) => { + if (e) { + ipcEmit('connection-alive', false); + socket.close(); + setTimeout(createSocket, 1000); + } + }); + + }, _connectionCheckTimeout); + if (openCallback) openCallback(); } @@ -59,7 +79,11 @@ export default function useWebSockets( const onClose = (event: WebSocket.CloseEvent) => { console.log("WS:Socket closed normally.", event.wasClean) + + clearInterval(_connectionCheckInterval); + if (!event.wasClean) { + ipcEmit('connection-alive', false); setTimeout(createSocket, 1000); } } @@ -69,8 +93,11 @@ export default function useWebSockets( console.log("WS:WebSocket error: ", event.message); } + const createSocket = (): WebSocket => { + if (_connectionCheckInterval) clearInterval(_connectionCheckInterval); + socket = new WebSocket(socketUrl); // Add listeners. @@ -78,6 +105,9 @@ export default function useWebSockets( socket.addEventListener("message", onServerMessage); socket.addEventListener("close", onClose); socket.addEventListener("error", onError); + socket.addEventListener("pong", () => { + ipcEmit('connection-alive', true); + }); return socket; -- 2.43.0