From 65bdb0abd7b4a58109b10d09228dd4adcfb3b437 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Sat, 16 Sep 2017 01:44:38 +0200 Subject: [PATCH] implemented socket close/reopen on window blur/focus to save server resources --- js/term.js | 18 +++++++++++++++--- js/term_conn.js | 19 ++++++++++++++++--- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/js/term.js b/js/term.js index 6847be5..e4d3b29 100644 --- a/js/term.js +++ b/js/term.js @@ -6,9 +6,21 @@ window.termInit = function ({ labels, theme, allFn }) { const termUpload = TermUpl(conn, input, screen) screen.input = input - conn.on('open', () => { screen.window.statusScreen = { title: 'Connecting', loading: true } }) - conn.on('connect', () => { screen.window.statusScreen = null }) - conn.on('disconnect', () => { screen.window.statusScreen = { title: 'Disconnected' } }) + // we delay the display of "connecting" to avoid flash when changing tabs with the terminal open + let showConnectingTimeout = -1 + conn.on('open', () => { + showConnectingTimeout = setTimeout(() => { + screen.window.statusScreen = { title: 'Connecting', loading: true } + }, 250) + }) + conn.on('connect', () => { + clearTimeout(showConnectingTimeout) + screen.window.statusScreen = null + }) + conn.on('disconnect', () => { + clearTimeout(showConnectingTimeout) + screen.window.statusScreen = { title: 'Disconnected' } + }) conn.on('silence', () => { screen.window.statusScreen = { title: 'Waiting for server', loading: true } }) // conn.on('ping-fail', () => { screen.window.statusScreen = { title: 'Disconnected' } }) conn.on('ping-success', () => { screen.window.statusScreen = { title: 'Re-connecting', loading: true } }) diff --git a/js/term_conn.js b/js/term_conn.js index efff328..35bda54 100644 --- a/js/term_conn.js +++ b/js/term_conn.js @@ -13,23 +13,37 @@ window.Conn = class TermConnection extends EventEmitter { this.forceClosing = false this.pageShown = false + + window.addEventListener('focus', () => { + console.info('Window got focus, re-connecting') + this.init() + }) + window.addEventListener('blur', () => { + console.info('Window lost focus, freeing socket') + this.closeSocket() + clearTimeout(this.heartbeatTimeout) + }) } onWSOpen (evt) { console.log('CONNECTED') this.heartbeat() this.send('i') + this.forceClosing = false this.emit('connect') } onWSClose (evt) { - if (this.forceClosing) return + if (this.forceClosing) { + this.forceClosing = false + return + } console.warn('SOCKET CLOSED, code ' + evt.code + '. Reconnecting...') if (evt.code < 1000) { console.error('Bad code from socket!') // this sometimes happens for unknown reasons, code < 1000 is invalid - location.reload() + // location.reload() } clearTimeout(this.reconnTimeout) @@ -109,7 +123,6 @@ window.Conn = class TermConnection extends EventEmitter { if (this.ws) { this.forceClosing = true this.ws.close() - this.forceClosing = false this.ws = null } }