(url?: string)
| 34 | } |
| 35 | |
| 36 | connect(url?: string): void { |
| 37 | if (url) this.url = url; |
| 38 | if (!this.url) throw new Error("No WebSocket URL provided"); |
| 39 | |
| 40 | this._closed = false; |
| 41 | this._ws = new WebSocket(this.url); |
| 42 | this._ws.binaryType = "arraybuffer"; |
| 43 | |
| 44 | this._ws.onopen = () => { |
| 45 | this._reconnectDelay = 1000; |
| 46 | this._flushBuffer(); |
| 47 | if (this.onOpen) this.onOpen(); |
| 48 | }; |
| 49 | |
| 50 | this._ws.onmessage = (event: MessageEvent) => { |
| 51 | if (this.onData) { |
| 52 | if (event.data instanceof ArrayBuffer) { |
| 53 | this.onData(new Uint8Array(event.data)); |
| 54 | } else { |
| 55 | this.onData(event.data as string); |
| 56 | } |
| 57 | } |
| 58 | }; |
| 59 | |
| 60 | this._ws.onclose = () => { |
| 61 | if (this.onClose) this.onClose(); |
| 62 | if (this.reconnect && !this._closed) this._scheduleReconnect(); |
| 63 | }; |
| 64 | |
| 65 | this._ws.onerror = (event) => { |
| 66 | if (this.onError) this.onError(event); |
| 67 | this._ws?.close(); |
| 68 | }; |
| 69 | } |
| 70 | |
| 71 | send(data: string | Uint8Array): void { |
| 72 | if (this._ws && this._ws.readyState === WebSocket.OPEN) { |
no test coverage detected