UNPKG

woolball-client

Version:

Client-side library for Woolball enabling secure browser resource sharing for distributed AI task processing

103 lines (102 loc) 3.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebSocketConnection = void 0; class WebSocketConnection { constructor(config) { this.socket = null; this.reconnectAttempts = 0; this.maxReconnectAttempts = 5; this.reconnectTimeout = 1000; // Start with 1 second this.config = config; this.connect(); } /** * Establishes connection to WebSocket server */ connect() { try { this.socket = new WebSocket(this.config.url); this.socket.onopen = () => { this.reconnectAttempts = 0; // Send client ID as soon as connection is established this.sendMessage({ type: 'REGISTER', data: { id: this.config.id } }); if (this.config.onOpen) { this.config.onOpen(); } }; this.socket.onmessage = (event) => { try { const message = JSON.parse(event.data); if (this.config.onMessage) { this.config.onMessage(message); } } catch (error) { console.error('Error parsing WebSocket message:', error); } }; this.socket.onerror = (error) => { console.error('WebSocket error:', error); if (this.config.onError) { this.config.onError(error); } }; this.socket.onclose = (event) => { console.log(`WebSocket connection closed: ${event.code} ${event.reason}`); if (this.config.onClose) { this.config.onClose(event); } // Attempt to reconnect if not a normal closure if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) { this.attemptReconnect(); } }; } catch (error) { console.error('Failed to establish WebSocket connection:', error); } } /** * Attempts to reconnect to the WebSocket server with exponential backoff */ attemptReconnect() { this.reconnectAttempts++; const delay = this.reconnectTimeout * Math.pow(2, this.reconnectAttempts - 1); console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`); setTimeout(() => { this.connect(); }, delay); } /** * Sends a message to the WebSocket server * @param message The message to send * @returns True if message was sent, false otherwise */ sendMessage(message) { if (this.socket && this.socket.readyState === WebSocket.OPEN) { this.socket.send(JSON.stringify(message)); return true; } return false; } /** * Closes the WebSocket connection */ disconnect() { if (this.socket) { this.socket.close(); this.socket = null; } } /** * Checks if the WebSocket connection is open * @returns True if connection is open, false otherwise */ isConnected() { return this.socket !== null && this.socket.readyState === WebSocket.OPEN; } } exports.WebSocketConnection = WebSocketConnection;