| 1 | const sockets = new Map(); |
| 2 | let next = 1; |
| 3 | |
| 4 | export function liveConnect(url, message, closed) { |
| 5 | const id = next++; |
| 6 | const socket = new WebSocket(url); |
| 7 | socket.binaryType = 'arraybuffer'; |
| 8 | socket.onmessage = event => message(event.data); |
| 9 | socket.onclose = () => { |
| 10 | if (!sockets.has(id)) return; |
| 11 | liveClose(id); |
| 12 | closed(); |
| 13 | }; |
| 14 | sockets.set(id, socket); |
| 15 | return id; |
| 16 | } |
| 17 | |
| 18 | export function liveSend(id, bytes) { |
| 19 | const socket = sockets.get(id); |
| 20 | try { |
| 21 | if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('Relay disconnected'); |
| 22 | if (socket.bufferedAmount > 1048576) throw new Error('Relay cannot keep up'); |
| 23 | socket.send(bytes); |
| 24 | } catch (error) { |
| 25 | socket?.onclose?.(); |
| 26 | throw error; |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | export function liveClose(id) { |
| 31 | const socket = sockets.get(id); |
| 32 | sockets.delete(id); |
| 33 | if (!socket) return; |
| 34 | socket.onmessage = socket.onclose = null; |
| 35 | socket.close(); |
| 36 | } |