implemented socket close/reopen on window blur/focus to save server resources

cpsdqs/unified-input
Ondřej Hruška 7 years ago
parent 2b4b364d0d
commit 65bdb0abd7
  1. 18
      js/term.js
  2. 19
      js/term_conn.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 } })

@ -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
}
}

Loading…
Cancel
Save