WebSockets & Real-Time Communication
How should you handle WebSocket reconnection in production applications?
class WebSocketClient {
constructor(url, options = {}) {
this.url = url;
this.options = {
reconnectInterval: 1000,
maxRetries: 5,
...options
};
this.retries = 0;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onclose = this.handleClose.bind(this);
}
handleClose() {
if (this.retries < this.options.maxRetries) {
this.retries++;
setTimeout(() => {
this.connect();
}, this.options.reconnectInterval * Math.pow(2, this.retries - 1));
}
}
}