UNPKG

camstreamerlib

Version:

Helper library for CamStreamer ACAP applications.

61 lines (60 loc) 1.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WsClient = void 0; const REFRESH_TIMEOUT = 5000; class WsClient { getUrl; isDestroyed = false; ws = null; restartTimeout = null; constructor(getUrl) { this.getUrl = getUrl; } init() { if (this.isDestroyed) { return; } this.destroyWebsocket(); const ws = new WebSocket(this.getUrl(), 'events'); ws.binaryType = 'arraybuffer'; ws.onopen = () => this.onOpen(); ws.onmessage = (e) => this.onMessage(e.data); ws.onclose = () => { this.restartTimeout = window.setTimeout(() => this.init(), REFRESH_TIMEOUT); }; this.ws = ws; } send = (msg) => { this.ws?.send(msg); }; onMessage = (_) => { }; onOpen = () => { }; onClose = () => { }; onError = (error) => { console.error(error); }; reconnect = () => { this.ws?.close(); }; destroy = () => { this.isDestroyed = true; this.destroyWebsocket(); }; destroyWebsocket() { if (this.restartTimeout !== null) { clearTimeout(this.restartTimeout); this.restartTimeout = null; } if (!this.ws) { return; } this.ws.onmessage = null; this.ws.onopen = null; this.ws.onclose = null; if (this.ws.readyState === this.ws.OPEN) { this.ws.close(); } this.ws = null; } } exports.WsClient = WsClient;