From 5d4ce4462745666f6410f2550162f3390b33444a Mon Sep 17 00:00:00 2001 From: softsimon Date: Fri, 6 Mar 2020 02:05:26 +0700 Subject: [PATCH] Introduce a websocket ping check that closes the socket if no response. --- backend/src/api/websocket-handler.ts | 4 +++ .../src/app/services/websocket.service.ts | 31 ++++++++++++++++--- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/backend/src/api/websocket-handler.ts b/backend/src/api/websocket-handler.ts index fc2096cc6..57ea4f32a 100644 --- a/backend/src/api/websocket-handler.ts +++ b/backend/src/api/websocket-handler.ts @@ -74,6 +74,10 @@ class WebsocketHandler { 'git-commit': this.latestGitCommitHash })); } + + if (parsedMessage.action === 'ping') { + client.send(JSON.stringify({'pong': true})); + } } catch (e) { console.log(e); } diff --git a/frontend/src/app/services/websocket.service.ts b/frontend/src/app/services/websocket.service.ts index 0104b79a0..98dd8656e 100644 --- a/frontend/src/app/services/websocket.service.ts +++ b/frontend/src/app/services/websocket.service.ts @@ -18,6 +18,8 @@ export class WebsocketService { private trackingTxId: string | null = null; private trackingAddress: string | null = null; private latestGitCommit = ''; + private onlineCheckTimeout: number; + private onlineCheckTimeoutTwo: number; constructor( private stateService: StateService, @@ -107,13 +109,12 @@ export class WebsocketService { } this.stateService.isOffline$.next(false); } + + this.startOnlineCheck(); }, (err: Error) => { console.log(err); - this.goneOffline = true; - this.stateService.isOffline$.next(true); - console.log('Error, retrying in 10 sec'); - window.setTimeout(() => this.startSubscription(), 10000); + this.goOffline(); }); } @@ -135,4 +136,26 @@ export class WebsocketService { this.websocketSubject.next({action: 'want', data: data}); this.lastWant = data; } + + goOffline() { + this.goneOffline = true; + this.stateService.isOffline$.next(true); + console.log('Error, retrying in 10 sec'); + window.setTimeout(() => this.startSubscription(), 10000); + } + + startOnlineCheck() { + clearTimeout(this.onlineCheckTimeout); + clearTimeout(this.onlineCheckTimeoutTwo); + + this.onlineCheckTimeout = window.setTimeout(() => { + this.websocketSubject.next({action: 'ping'}); + this.onlineCheckTimeoutTwo = window.setTimeout(() => { + if (!this.goneOffline) { + this.websocketSubject.complete(); + this.goOffline(); + } + }, 1000); + }, 10000); + } }