diff options
author | Maximilien Cuony <maximilien@theglu.org> | 2016-09-11 11:47:07 +0200 |
---|---|---|
committer | Maximilien Cuony <maximilien@theglu.org> | 2016-09-11 11:47:07 +0200 |
commit | e25b790a4b992808e75387615e209273ffe94cd1 (patch) | |
tree | 66910688f261c304d121fd16b4c4654f1f47f928 /templates | |
parent | 007ea5571e2dca4d2ce6db7b3e7f98b86bf929ab (diff) | |
download | glutte-serial-web-e25b790a4b992808e75387615e209273ffe94cd1.tar.gz glutte-serial-web-e25b790a4b992808e75387615e209273ffe94cd1.tar.bz2 glutte-serial-web-e25b790a4b992808e75387615e209273ffe94cd1.zip |
More rebust websocket connection
Diffstat (limited to 'templates')
-rw-r--r-- | templates/index.html | 70 |
1 files changed, 66 insertions, 4 deletions
diff --git a/templates/index.html b/templates/index.html index 038130d..0cf5a09 100644 --- a/templates/index.html +++ b/templates/index.html @@ -11,12 +11,74 @@ <script> var output = document.getElementById('output'); - var socket = new WebSocket("ws://" + window.location.host + "/stream"); + var socket = null; + var closed = true; + var retry_scheduled = false; - socket.onmessage = function(data) { - output.textContent += data.data; - window.scrollTo(0, document.body.scrollHeight); + function init_socket() { + + retry_scheduled = false; + + if (socket != null) { + + socket.onmessage = null; + socket.onopen = null; + socket.onclose = null; + socket.onerror = null; + + delete socket; + } + + socket = new WebSocket("ws://" + window.location.host + "/stream"); + + socket.onmessage = function(data) { + output.textContent += data.data; + window.scrollTo(0, document.body.scrollHeight); + } + + socket.onopen = function(data) { + output.textContent += "{System} Websocket open !\n"; + window.scrollTo(0, document.body.scrollHeight); + closed = false; + } + + socket.onclose = function(code, text) { + closed = true; + if (!retry_scheduled) { + output.textContent += "{System} Websocket closed :( " + text + "\n"; + window.scrollTo(0, document.body.scrollHeight); + retry_scheduled = true; + init_socket(); + } + } + + socket.onerror = function() { + closed = true; + + if (!retry_scheduled) { + output.textContent += "{System} Websocket error. Trying again in 3s :(\n"; + window.scrollTo(0, document.body.scrollHeight); + setTimeout(init_socket, 3000); + retry_scheduled = true; + } + } + + } + + function keep_alive() { + + if (!closed) { + try { + socket.send('.'); + } catch (e) { + } + } + + setTimeout(keep_alive, 10000); } + + init_socket(); + keep_alive(); </script> </body> </html> |