JavaScript Development Space

How to Implement Reliable WebSocket Reconnection Logic with Ease

WebSockets are a powerful tool for real-time communication between a client and a server. However, handling connection interruptions and ensuring reliability can be challenging. This guide demonstrates how to implement a robust WebSocket encapsulation with automatic reconnection, event listeners, and customizable parameters.

Why Encapsulate WebSocket Logic?

By encapsulating WebSocket logic, you:

  • Simplify implementation across your app.
  • Handle reconnection automatically without duplicating code.
  • Improve maintainability and scalability.

Key Features of the WebSocket Encapsulation

  1. Automatic Reconnection: Retry connecting after disconnections with configurable parameters.
  2. Event Listeners: Add and manage WebSocket events like open, close, and error.
  3. Customizable Parameters: Control maximum reconnection attempts, intervals, and timeout limits.
  4. Error Handling: Gracefully handle errors and provide feedback.

Implementation: WebSocketReconnect Class

Below is the complete implementation of a WebSocketReconnect class:

js
1 class WebSocketReconnect {
2 constructor(
3 url,
4 maxReconnectAttempts = 3,
5 reconnectInterval = 20000,
6 maxReconnectTime = 180000
7 ) {
8 this.url = url;
9 this.maxReconnectAttempts = maxReconnectAttempts;
10 this.reconnectInterval = reconnectInterval;
11 this.maxReconnectTime = maxReconnectTime;
12 this.reconnectCount = 0;
13 this.reconnectTimeout = null;
14 this.startTime = null;
15 this.socket = null;
16 this.listenerEvents = {};
17
18 if (this.checkWssUrl()) {
19 this.connect();
20 }
21 }
22
23 checkWssUrl(url = this.url) {
24 if (/wss:\/\/.*/.test(url) || /ws:\/\/.*/.test(url)) {
25 return true;
26 } else {
27 console.error("Invalid WebSocket URL");
28 return false;
29 }
30 }
31
32 connect() {
33 console.log("Connecting...");
34 this.socket = new WebSocket(this.url);
35
36 this.socket.onopen = () => {
37 console.log("WebSocket Connection Opened");
38 this.triggerEvent("open");
39 this.clearReconnectTimeout();
40 this.reconnectCount = 0;
41 };
42
43 this.socket.onclose = (event) => {
44 console.log("WebSocket Connection Closed", event);
45 this.triggerEvent("close");
46 this.handleReconnect();
47 };
48
49 this.socket.onerror = (error) => {
50 console.error("WebSocket Error", error);
51 this.triggerEvent("error");
52 this.handleReconnect();
53 };
54 }
55
56 triggerEvent(type) {
57 const events = this.listenerEvents[type] || [];
58 events.forEach((callback) => callback());
59 }
60
61 addEventListener(type, callback) {
62 if (!this.listenerEvents[type]) {
63 this.listenerEvents[type] = [];
64 }
65 this.listenerEvents[type].push(callback);
66 }
67
68 handleReconnect() {
69 if (
70 this.reconnectCount < this.maxReconnectAttempts &&
71 (!this.startTime || Date.now() - this.startTime < this.maxReconnectTime)
72 ) {
73 this.reconnectCount++;
74 console.log(`Reconnecting (${this.reconnectCount}/${this.maxReconnectAttempts})...`);
75
76 this.reconnectTimeout = setTimeout(() => {
77 this.connect();
78 }, this.reconnectInterval);
79
80 if (!this.startTime) {
81 this.startTime = Date.now();
82 }
83 } else {
84 console.log("Max reconnection attempts reached or timeout exceeded.");
85 }
86 }
87
88 clearReconnectTimeout() {
89 if (this.reconnectTimeout) {
90 clearTimeout(this.reconnectTimeout);
91 this.reconnectTimeout = null;
92 }
93 }
94
95 close() {
96 if (this.socket && this.socket.readyState === WebSocket.OPEN) {
97 this.socket.close();
98 }
99 this.clearReconnectTimeout();
100 this.reconnectCount = 0;
101 this.startTime = null;
102 }
103 }

Example Usage

Here’s how you can use the WebSocketReconnect class:

js
1 import WebSocketReconnect from './WebSocketReconnect';
2
3 const ws = new WebSocketReconnect('ws://your-websocket-url');
4
5 ws.addEventListener('open', () => {
6 console.log('WebSocket opened');
7 });
8
9 ws.addEventListener('close', () => {
10 console.log('WebSocket closed');
11 });
12
13 ws.addEventListener('error', () => {
14 console.log('WebSocket encountered an error');
15 });
16
17 // Close the WebSocket connection when no longer needed
18 ws.close();

Key Methods Explained

  1. connect: Establishes the WebSocket connection and sets event listeners.
  2. handleReconnect: Implements reconnection logic with retry limits.
  3. addEventListener: Registers event listeners for WebSocket events.
  4. close: Closes the WebSocket connection and clears reconnection timers.

Benefits of Using This Encapsulation

  • Reduced Boilerplate: Write less repetitive code for WebSocket management.
  • Improved Reliability: Automatically recover from connection disruptions.
  • Flexibility: Customize parameters like retry limits and intervals.

By following this guide, you can implement a reliable WebSocket encapsulation that simplifies handling real-time connections in your applications.

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.