Created
October 21, 2025 18:31
-
-
Save recidive/3e056ff6a73848796228fe467bbb9f26 to your computer and use it in GitHub Desktop.
ReconnectingWebSocket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ReconnectingWebSocket { | |
| constructor(url) { | |
| this.url = url; | |
| this.ws = null; | |
| this.reconnectAttempts = 0; | |
| this.maxReconnectAttempts = 10; | |
| this.reconnectInterval = 1000; // Initial delay in ms | |
| this.connect(); | |
| } | |
| connect() { | |
| this.ws = new WebSocket(this.url); | |
| this.ws.onopen = () => { | |
| console.log('WebSocket connected'); | |
| this.reconnectAttempts = 0; // Reset attempts on successful connection | |
| // ... handle open event | |
| }; | |
| this.ws.onmessage = (event) => { | |
| console.log('Received:', event.data); | |
| // ... handle message | |
| }; | |
| this.ws.onclose = () => { | |
| console.warn('WebSocket closed. Reconnecting...'); | |
| this.reconnect(); | |
| }; | |
| this.ws.onerror = (error) => { | |
| console.error('WebSocket error:', error); | |
| // Optionally, close the socket to trigger onclose and reconnect | |
| this.ws.close(); | |
| }; | |
| } | |
| reconnect() { | |
| if (this.reconnectAttempts < this.maxReconnectAttempts) { | |
| this.reconnectAttempts++; | |
| const delay = this.reconnectInterval * Math.pow(2, this.reconnectAttempts - 1); // Exponential backoff | |
| const jitter = Math.random() * delay * 0.2; // Add 20% random jitter | |
| const finalDelay = delay + jitter; | |
| setTimeout(() => { | |
| console.log(`Attempting reconnection ${this.reconnectAttempts} in ${finalDelay.toFixed(0)}ms...`); | |
| this.connect(); | |
| }, finalDelay); | |
| } else { | |
| console.error('Max reconnection attempts reached. Giving up.'); | |
| // ... handle permanent disconnection (e.g., notify user) | |
| } | |
| } | |
| } | |
| // Usage: | |
| // const socket = new ReconnectingWebSocket('ws://localhost:8080'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment