Reconnection of Client when server reboots in WebSocket

Reconnection of Client when server reboots in WebSocket

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Server Reboots in WebSocket Connections

When a client maintains an active WebSocket connection and the server undergoes a reboot, the network stack on that server is effectively wiped clean. The TCP session established between the PHP process and the Chrome browser is severed at the socket level. From the application logic perspective, this manifests as an abrupt closure or a timeout error rather than a graceful shutdown sequence.

The specific scenario described involves using phpwebsocket with PHP5 to handle real-time chat. When you kill the server process (kill) and restart it, the client immediately detects the disconnection. The core challenge is determining how the client should react to this event. Should the page refresh automatically? Or should the JavaScript layer attempt to re-establish the connection before allowing user interaction?

Understanding the Disconnection Event

In a standard WebSocket implementation like phpwebsocket, the server does not send a graceful close frame (opcode 8) when it is forcibly killed. Instead, the TCP connection is reset by the operating system. When the client receives this abrupt termination, the underlying WebSocket library on the client side throws an error or triggers an event indicating that the connection is closed due to a network error or host unreachable.

If you rely solely on the onclose event in your JavaScript code without further action, the application state becomes stale. The user might be typing a message, but that data sits in the input buffer until they hit enter, which often fails silently if the connection is already marked as closed.

Implementing Automatic Reconnection Logic

The most robust approach for real-time applications is to implement an automatic reconnection strategy within the client-side JavaScript. This avoids the need to refresh the page or manually intervene when a server restart occurs.

When the onclose event fires, you must check the code and reason provided by the browser or your WebSocket library. A network error (often code 1006) indicates a hard disconnect. Your logic should follow this pattern:

const ws = new WebSocket('ws://your-server-address');

ws.onclose = function(e) {
    // Check if the connection was closed due to a network issue or server restart
    if (e.code === 1006 || e.code === 1011) {
        attemptReconnect();
    }
};

function attemptReconnect() {
    const reconnectDelay = 2000; // Wait 2 seconds before retrying
    
    setTimeout(() => {
        console.log('Attempting to reconnect...');
        ws = new WebSocket('ws://your-server-address');
        
        ws.onopen = function(event) {
            console.log('Reconnected successfully');
            // Resume sending messages or updating UI state here
        };
        
        ws.onerror = function(error) {
            console.error('Reconnection failed:', error);
            attemptReconnect(); // Retry after a delay (optional backoff logic can be added here)
        };
        
        ws.onclose = function(e) {
            // Handle persistent disconnections if needed
        };
    }, reconnectDelay);
}

This pattern ensures that when the server is killed and restarted, the client detects the loss of connection and immediately attempts to re-establish the link. Once the onopen event fires, the application resumes normal operation without user intervention.

Trade-offs and Configuration Considerations

While automatic reconnection is seamless for the user, it introduces complexity in managing state. If a user sends a message just before the server dies, that message will arrive after the server restarts only if the client successfully reconnects. However, since the server process was killed, any unsaved session data on the server side (like an in-memory queue) is lost. The reconnected client will simply receive the next available messages from the restarted server.

Another consideration is the frequency of reconnection attempts. A naive implementation that retries every 100ms during a prolonged outage can flood your server with new connections once it comes back online, potentially exhausting connection pools or causing memory spikes in the PHP process. Implementing an exponential backoff strategy—waiting 2 seconds, then 4, then 8, up to a maximum cap—is standard practice to mitigate this risk.

Furthermore, relying on a page refresh as a fallback is generally discouraged for WebSocket applications because it disrupts the user experience and requires re-initializing all application logic, which can be inefficient compared to a direct socket reconnection.

If you are building a larger framework or need more robust infrastructure for managing these connections, platforms like Laravel provide built-in abstractions that handle many of these edge cases through their event dispatching system. For instance, integrating phpwebsocket into a Laravel application allows you to hook into the server lifecycle and broadcast events that clients can listen to, ensuring that reconnection logic is handled consistently across different environments.

Our network