How to reconnect to websocket after close connection with HTML?

WebSockets are designed to maintain persistent connections, but they can close due to network issues, server restarts, or connection timeouts. When a WebSocket connection closes, you need to manually recreate the socket to reconnect.

How WebSocket Reconnection Works

When a WebSocket connection closes, the onclose event fires. You can handle this event to automatically attempt reconnection by creating a new WebSocket instance and reattaching event listeners.

Basic Reconnection Example

<script>
// Socket Variable declaration
var mySocket;

const socketMessageListener = (event) => {
    console.log('Received:', event.data);
};

// Connection opened
const socketOpenListener = (event) => {
    console.log('Connected to WebSocket');
    mySocket.send('Hello Server!');
};

// Connection closed - auto reconnect
const socketCloseListener = (event) => {
    if (mySocket) {
        console.log('Disconnected. Attempting to reconnect...');
    }
    
    // Create new WebSocket connection
    mySocket = new WebSocket('ws://localhost:8080');
    mySocket.addEventListener('open', socketOpenListener);
    mySocket.addEventListener('message', socketMessageListener);
    mySocket.addEventListener('close', socketCloseListener);
    mySocket.addEventListener('error', (error) => {
        console.error('WebSocket error:', error);
    });
};

// Initial connection
socketCloseListener();
</script>

Enhanced Reconnection with Retry Logic

For production applications, implement retry delays and maximum retry attempts to prevent overwhelming the server:

<script>
var mySocket;
var reconnectAttempts = 0;
var maxReconnectAttempts = 5;
var reconnectDelay = 1000; // Start with 1 second

const connectWebSocket = () => {
    mySocket = new WebSocket('ws://localhost:8080');
    
    mySocket.addEventListener('open', () => {
        console.log('WebSocket connected');
        reconnectAttempts = 0; // Reset counter on successful connection
        reconnectDelay = 1000; // Reset delay
    });
    
    mySocket.addEventListener('message', (event) => {
        console.log('Message received:', event.data);
    });
    
    mySocket.addEventListener('close', () => {
        console.log('WebSocket disconnected');
        attemptReconnect();
    });
    
    mySocket.addEventListener('error', (error) => {
        console.error('WebSocket error:', error);
    });
};

const attemptReconnect = () => {
    if (reconnectAttempts < maxReconnectAttempts) {
        reconnectAttempts++;
        console.log(`Reconnection attempt ${reconnectAttempts}/${maxReconnectAttempts} in ${reconnectDelay}ms`);
        
        setTimeout(() => {
            connectWebSocket();
            reconnectDelay *= 2; // Exponential backoff
        }, reconnectDelay);
    } else {
        console.error('Max reconnection attempts reached');
    }
};

// Initial connection
connectWebSocket();
</script>

Key Points

  • Automatic Reconnection: Handle the close event to trigger reconnection
  • Exponential Backoff: Increase delay between reconnection attempts to avoid server overload
  • Maximum Attempts: Limit reconnection attempts to prevent infinite loops
  • Error Handling: Always include error event listeners for better debugging

Conclusion

WebSocket reconnection requires manually recreating the socket when the connection closes. Implement retry logic with exponential backoff and maximum attempts for robust production applications.

Updated on: 2026-03-15T23:18:59+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements