/** * WebSocket signaling client for WebRTC SDP/ICE exchange. * * Connects to the signaling server and relays offers, answers, and ICE * candidates between peers. The signaling server is a simple JSON relay * (see browser/signaling-server/server.js). */ export class SignalingClient { /** @type {WebSocket | null} */ #ws = null; /** @type {string} */ #url; /** @type {string} */ #peerId; /** @type {Map} */ #handlers = new Map(); /** @type {boolean} */ #connected = false; /** @type {number | null} */ #heartbeatTimer = null; /** * @param {string} url - WebSocket URL of the signaling server * @param {string} peerId - This peer's unique ID */ constructor(url, peerId) { this.#url = url; this.#peerId = peerId; } get connected() { return this.#connected; } get peerId() { return this.#peerId; } /** Connect to the signaling server. */ connect() { return new Promise((resolve, reject) => { this.#ws = new WebSocket(this.#url); this.#ws.onopen = () => { this.#connected = true; // Register our peer ID with the server this.#send({ type: 'register', peerId: this.#peerId }); // Start heartbeat this.#heartbeatTimer = setInterval(() => { if (this.#connected) this.#send({ type: 'ping' }); }, 30_000); resolve(); }; this.#ws.onmessage = (event) => { try { const msg = JSON.parse(event.data); this.#dispatch(msg.type, msg); } catch (e) { console.warn('[signaling] Failed to parse message:', e); } }; this.#ws.onclose = () => { this.#connected = false; this.#stopHeartbeat(); this.#dispatch('disconnect', {}); }; this.#ws.onerror = (err) => { if (!this.#connected) reject(err); this.#dispatch('error', { error: err }); }; }); } /** Disconnect from the signaling server. */ disconnect() { this.#stopHeartbeat(); if (this.#ws) { this.#ws.close(); this.#ws = null; } this.#connected = false; } /** Send an SDP offer to a remote peer. */ sendOffer(to, sdp) { this.#send({ type: 'offer', to, sdp }); } /** Send an SDP answer to a remote peer. */ sendAnswer(to, sdp) { this.#send({ type: 'answer', to, sdp }); } /** Send an ICE candidate to a remote peer. */ sendCandidate(to, candidate, sdpMid) { this.#send({ type: 'candidate', to, candidate, sdpMid }); } /** * Register an event handler. * @param {'offer'|'answer'|'candidate'|'error'|'disconnect'} type * @param {Function} handler */ on(type, handler) { if (!this.#handlers.has(type)) this.#handlers.set(type, []); this.#handlers.get(type).push(handler); } /** Remove all handlers for a given event type. */ off(type) { this.#handlers.delete(type); } #send(msg) { if (this.#ws && this.#ws.readyState === WebSocket.OPEN) { this.#ws.send(JSON.stringify(msg)); } } #dispatch(type, msg) { const handlers = this.#handlers.get(type); if (handlers) { for (const handler of handlers) handler(msg); } } #stopHeartbeat() { if (this.#heartbeatTimer !== null) { clearInterval(this.#heartbeatTimer); this.#heartbeatTimer = null; } } }