diff options
author | Adam Hovorka <[email protected]> | 2019-07-17 23:23:52 -0600 |
---|---|---|
committer | Adam Hovorka <[email protected]> | 2019-07-17 23:23:52 -0600 |
commit | 1216a517b7f725c787609db453eaa48f99c92918 (patch) | |
tree | 16c53c5c008d94217d35306891dcb0634c0b63b5 /public/sock.js | |
parent | 4f858ebf3206431447177c977533d18dbea6dca9 (diff) |
Flesh out the WebSocket system with some amenities
Diffstat (limited to 'public/sock.js')
-rw-r--r-- | public/sock.js | 43 |
1 files changed, 43 insertions, 0 deletions
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 })(); |