From abe3c9f8aa68346eec2050a546c77db31a02f077 Mon Sep 17 00:00:00 2001 From: Annika Backstrom Date: Sun, 9 Apr 2017 22:02:55 -0400 Subject: [PATCH] attempt client reconnection of closed websockets --- static/jukebox.js | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/static/jukebox.js b/static/jukebox.js index 0166677..d3b9807 100644 --- a/static/jukebox.js +++ b/static/jukebox.js @@ -1,18 +1,31 @@ window.onload = function() { - console.log('window.onload'); + var play_log = document.getElementById('play-log'); + var last_tag = document.getElementById('last-tag'); - var play_log = document.getElementById('play-log'); - var last_tag = document.getElementById('last-tag'); + function updateLog(data) { + last_tag.innerHTML = data.tag; + play_log.innerHTML = data.html; + } - function updateLog(data) { - last_tag.innerHTML = data.tag; - play_log.innerHTML = data.html; + var host = window.document.location.host.replace(/:.*/, ''); + var ws; + + function connectWebsocket() { + console.log('Attempting WebSocket connection...'); + ws = new WebSocket('ws://' + host + ':' + jukebox.port); + ws.addEventListener('open', function(event) { + console.log('WebSocket connection opened.'); + }); + ws.addEventListener('message', function(event) { + updateLog(JSON.parse(event.data)); + }); + } + + setInterval(function() { + if (ws.readyState == WebSocket.CLOSED) { + connectWebsocket(); } + }, 1000); - var host = window.document.location.host.replace(/:.*/, ''); - var ws = new WebSocket('ws://' + host + ':' + jukebox.port); - ws.onmessage = function (event) { - updateLog(JSON.parse(event.data)); - }; - + connectWebsocket(); };