| 1 | import { useState, useRef, useEffect } from "react"; |
| 2 | |
| 3 | export const useWebsocket = (onEvent) => { |
| 4 | const ws = useRef(null); |
| 5 | const [ seq, setSeq ] = useState(0); |
| 6 | const [ registry, setRegistry ] = useState({}); |
| 7 | |
| 8 | const createWebSocket = (url) => { |
| 9 | try { |
| 10 | ws.current = new WebSocket(url); |
| 11 | ws.current.onclose = (e) => { |
| 12 | onEvent._onclose && onEvent._onclose(e); |
| 13 | ws.current = null; |
| 14 | }; |
| 15 | ws.current.onerror = (e) => { |
| 16 | onEvent._onerror && onEvent._onerror(`there was an error with your websocket`); |
| 17 | }; |
| 18 | ws.current.onmessage = ({ data }) => { |
| 19 | const parsed = JSON.parse(data); |
| 20 | if (parsed.ty && parsed.ty === "event") { |
| 21 | if (parsed.event === "stop") { |
| 22 | let rest = registry; |
| 23 | delete rest[parsed.seq_id]; |
| 24 | setRegistry(rest); |
| 25 | } else { |
| 26 | onEvent[parsed.event](parsed); |
| 27 | } |
| 28 | } else if (parsed.ty && parsed.ty === "response") { |
| 29 | if (!(parsed.seq_id in registry)) |
| 30 | return; |
| 31 | for (const callback of registry[parsed.seq_id]) { |
| 32 | callback(parsed); |
| 33 | } |
| 34 | } |
| 35 | }; |
| 36 | } catch (e) { |
| 37 | onEvent._onerror && onEvent._onerror(`connect ${url} fault`); |
| 38 | ws.current = null; |
| 39 | } |
| 40 | }; |
| 41 | |
| 42 | const connect = (url) => { |
| 43 | if (!ws.current) { |
| 44 | createWebSocket(url); |
| 45 | } |
| 46 | }; |
| 47 | |
| 48 | const disconnect = () => { |
| 49 | ws.current && ws.current.close(); |
| 50 | }; |
| 51 | |
| 52 | const send = (seq_id, msg, callback=undefined) => { |
| 53 | msg.ty = 'request'; |
| 54 | if (seq_id >= 0) |
| 55 | msg.seq_id = seq_id; |
| 56 | else { |
| 57 | msg.seq_id = seq; |
| 58 | setSeq(seq + 1); |
| 59 | } |
| 60 | let tmp = registry; |