| 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) { |