From dda07160531339ed40aa5f687003cc3d15baf245 Mon Sep 17 00:00:00 2001 From: "Sascha L. Teichmann" Date: Fri, 13 Mar 2015 12:29:55 +0100 Subject: [PATCH] To keep websockets alive send every eight seconds a ping to the server. --- cmd/mtwebmapper/web/js/auto-update.js | 36 ++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/cmd/mtwebmapper/web/js/auto-update.js b/cmd/mtwebmapper/web/js/auto-update.js index 89ca8af..bb6b806 100644 --- a/cmd/mtwebmapper/web/js/auto-update.js +++ b/cmd/mtwebmapper/web/js/auto-update.js @@ -15,9 +15,7 @@ L.Control.AutoUpdate = L.Control.extend({ return container; }, - cbClick: function (e) { - L.DomEvent.stopPropagation(e); - this.intendedFunction(this.pressed); + switchButtons: function() { if (this.pressed) { this.pressed = false; this.iconStart.setAttribute('class', 'fa fa-pause'); @@ -29,18 +27,48 @@ L.Control.AutoUpdate = L.Control.extend({ } }, + cbClick: function (e) { + L.DomEvent.stopPropagation(e); + this.intendedFunction(this.pressed); + this.switchButtons(); + }, + intendedFunction: function() { alert('no function selected'); }, stopUpdate: function() { - this.socket.close(); + if (this.socket) { + this.socket.close(); + this.socket = null; + } }, autoUpdate: function() { var me = this; this.socket = new WebSocket('ws://' + window.location.host + '/ws'); + this.socket.onerror = function(evt) { + me.stopUpdate(); + me.switchButtons(); + }; + + this.socket.onclose = this.socket.onerror; + + this.socket.onopen = function(evt) { + // Sending pings every 5 secs to keep connection alive. + var heartbeat = function() { + if (heartbeat && me.socket) { + me.socket.send("PING"); + setTimeout(heartbeat, 8000); + } else { + // Prevent sending pings to re-opened sockets. + heartbeat = null; + } + }; + setTimeout(heartbeat, 8000); + }; + this.socket.onmessage = function(evt) { var updatePlayers = function(json) {