From abb122e2a9215b212511ecb9c33b3452e31adc9c Mon Sep 17 00:00:00 2001 From: azivner Date: Sun, 26 Nov 2017 13:22:26 -0500 Subject: [PATCH] websocket reconnection --- public/javascripts/init.js | 42 ++++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/public/javascripts/init.js b/public/javascripts/init.js index eeb896d52..20bedeff8 100644 --- a/public/javascripts/init.js +++ b/public/javascripts/init.js @@ -141,12 +141,7 @@ function initAjax() { initAjax(); -// use wss for secure messaging -const ws = new WebSocket("ws://" + location.host); -ws.onopen = function (event) { -}; - -ws.onmessage = function (event) { +function messageHandler(event) { console.log(event.data); const message = JSON.parse(event.data); @@ -170,12 +165,43 @@ ws.onmessage = function (event) { const changesToPushCountEl = $("#changesToPushCount"); changesToPushCountEl.html(message.changesToPushCount); } -}; +} + +let ws = null; + +function connectWebSocket() { + // use wss for secure messaging + ws = new WebSocket("ws://" + location.host); + ws.onopen = function (event) {}; + ws.onmessage = messageHandler; + ws.onclose = function(){ + // Try to reconnect in 5 seconds + setTimeout(() => connectWebSocket(), 1000); + }; +} + +connectWebSocket(); let lastPingTs = new Date().getTime(); +let connectionBrokenNotification = null; setInterval(() => { if (new Date().getTime() - lastPingTs > 5000) { - showError("No communication with server"); + if (!connectionBrokenNotification) { + connectionBrokenNotification = $.notify({ + // options + message: "Lost connection to server" + },{ + // settings + type: 'danger', + delay: 100000000 + }); + } + } + else if (connectionBrokenNotification) { + connectionBrokenNotification.close(); + connectionBrokenNotification = null; + + showMessage("Re-connected to server"); } }, 3000); \ No newline at end of file