From 1216a517b7f725c787609db453eaa48f99c92918 Mon Sep 17 00:00:00 2001 From: Adam Hovorka Date: Wed, 17 Jul 2019 23:23:52 -0600 Subject: Flesh out the WebSocket system with some amenities --- public/sock.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 public/sock.js (limited to 'public/sock.js') diff --git a/public/sock.js b/public/sock.js new file mode 100644 index 0000000..8cc73f0 --- /dev/null +++ b/public/sock.js @@ -0,0 +1,43 @@ +const sock = (() => { "use strict" +const refresh = () => setTimeout(() => location.reload(), 1e3); + +let ws, pingTimeout; +const prequeue = []; +const handlers = { + "reset": [refresh], + "ping": [() => { + clearTimeout(pingTimeout); + pingTimeout = setTimeout(refresh, 3e4); + sock.send("pong", {}); + }], +}; + +const sock = { + init: url => { + ws = new WebSocket(url); + ws.addEventListener("close", refresh); + ws.addEventListener("error", refresh); + ws.addEventListener("message", e => { + const d = JSON.parse(e.data); + (handlers[d.type]||[]).forEach(cb => cb(d.data)); + }); + ws.addEventListener("open", e => { + while (prequeue.length) sock.send(...prequeue.shift()); + (handlers["open"]||[]).forEach(cb => cb()); + delete handlers["open"]; + }); + }, + + on: (type, cb) => { + if (type === "open" && ws && ws.readyState === WebSocket.OPEN) cb(); + else (handlers[type]||(handlers[type]=[])).push(cb); + }, + + send: (type, data) => { + if (ws && ws.readyState === WebSocket.OPEN) + ws.send(JSON.stringify({type, data})); + else prequeue.push([type, data]); + }, +}; + +return sock })(); -- cgit v1.2.3-54-g00ecf