UNPKG

camstreamerlib

Version:

Helper library for CamStreamer ACAP applications.

59 lines (58 loc) 1.6 kB
const REFRESH_TIMEOUT = 5_000; export class WsClient { getUrl; getAuthToken; isDestroyed = false; ws = null; restartTimeout = null; constructor(getUrl, getAuthToken) { this.getUrl = getUrl; this.getAuthToken = getAuthToken; } init() { if (this.isDestroyed) { return; } this.destroyWebsocket(); const ws = new WebSocket(this.getUrl(), 'events'); ws.onopen = async () => { try { const token = await this.getAuthToken(); ws.send(JSON.stringify({ authorization: token })); } catch (error) { console.error('Error sending auth token:', error); ws.close(); } }; ws.onmessage = (e) => this.onmessage(e); ws.onclose = () => { this.restartTimeout = window.setTimeout(() => this.init(), REFRESH_TIMEOUT); }; this.ws = ws; } send = (msg) => { this.ws?.send(msg); }; onmessage = (_) => { }; 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; } }