From 8fa7260a5bbf332312fa3ba77e2a60d8b60054ac Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 7 Oct 2018 23:58:00 +0300 Subject: Server Side Events: server and webapp --- juick-server/src/main/assets/scripts.js | 71 +++++++-------------------------- 1 file changed, 15 insertions(+), 56 deletions(-) (limited to 'juick-server/src/main/assets') diff --git a/juick-server/src/main/assets/scripts.js b/juick-server/src/main/assets/scripts.js index 1f2efd33..995a396a 100644 --- a/juick-server/src/main/assets/scripts.js +++ b/juick-server/src/main/assets/scripts.js @@ -122,27 +122,17 @@ function i18n(key, lang = undefined) { || key; } -var ws, - pageTitle; +var es, pageTitle; -function initWS() { - let url = new URL('/ws/', window.location.href); - url.protocol = url.protocol.replace('http', 'ws'); +function initES() { + let url = new URL('/api/events', window.location.href); let hash = document.getElementById('body').getAttribute('data-hash'); if (hash) { url += '?hash=' + hash; - } else { - let content = document.getElementById('content'); - if (content) { - let pageMID = content.getAttribute('data-mid'); - if (pageMID) { - url += pageMID; - } - } } - ws = new WebSocket(url); - ws.onopen = function() { + es = new EventSource(url); + es.onopen = function() { console.log('online'); if (!document.querySelector('#wsthread')) { var d = document.createElement('div'); @@ -152,47 +142,18 @@ function initWS() { pageTitle = document.title; } }; - ws.onclose = function() { - console.log('offline'); - ws = false; - setTimeout(function() { - initWS(); - }, 2000); - }; - ws.onmessage = function(msg) { - if (msg.data == ' ') { - ws.send(' '); - } else { - try { - var jsonMsg = JSON.parse(msg.data); - console.log('data: ' + msg.data); - if (jsonMsg.service) { - return; - } - wsIncomingReply(jsonMsg); - } catch (err) { - console.log(err); + es.onmessage = function(msg) { + try { + var jsonMsg = JSON.parse(msg.data); + console.log('data: ' + msg.data); + if (jsonMsg.service) { + return; } + wsIncomingReply(jsonMsg); + } catch (err) { + console.log(err); } }; - var keepAlive = setInterval(wsSendKeepAlive, 90000); - window.addEventListener('beforeunload', () => { - clearInterval(keepAlive); - ws.close(); - }); -} - -function wsSendKeepAlive() { - if (ws) { - ws.send(' '); - } -} - -function wsShutdown() { - if (ws) { - ws.onclose = function() { }; - ws.close(); - } } function wsIncomingReply(msg) { @@ -896,9 +857,7 @@ ready(function() { }); } }); - initWS(); - - window.addEventListener('pagehide', wsShutdown); + initES(); killy.embedAll(); var elSelector = 'header', -- cgit v1.2.3