Reconnection and Connection Status
🎯 Introduction
User A is receiving room1 messages when the server suddenly restarts. The client needs to report the disconnection and rejoin the room once the service returns. This article uses the authentication chapter's server and verifies the process by stopping and restarting it.
🧱 What Must Happen After Automatic Reconnection?
When the network fails or the service stops unexpectedly, the Socket.IO client attempts to reconnect by default. A successful reconnection triggers the client's connect event again.
Restarting the server process clears its previous connections and room memberships. After connecting again, the client must request to rejoin room1 and wait for acknowledgement before continuing to receive its messages.
The previous article already placed joining in the connect callback, which also works for reconnection. However, that demonstration automatically sent “Hello” after joining. Keeping that code would resend the greeting after every reconnection. Here, User A only restores its subscription, and User B sends messages to verify reception.
| Client event | Meaning in this experiment |
|---|---|
| connect | Initial connection or reconnection succeeded; request to join the room next |
| disconnect | The previous connection has closed |
| connect_error | A connection attempt failed |
🛠 Display Status and Rejoin the Room
Replace User A's client.mjs with the following code. Keep the previous server's authentication and room handlers.
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000', {
auth: { token: 'demo-token-a' }
});
const room = 'room1';
socket.on('connect', () => {
console.log('Connected, joining room');
socket.timeout(3000).emit('room:join', room, (error, result) => {
if (error) {
console.log('Joining room timed out');
return;
}
console.log(result.ok ? `Joined ${result.room}` : result.error);
});
});
socket.on('disconnect', (reason) => {
console.log('Disconnected', reason);
});
socket.on('connect_error', (error) => {
console.log('Connection failed', error.message);
});
socket.on('chat:message', (message) => {
console.log(`[User ${message.senderId}] ${message.text}`);
});
connect runs after every successful connection, so rejoining belongs here. Register chat:message once outside it; that listener remains active after reconnection. Registering it inside connect would add another listener on every reconnection, potentially printing one message multiple times.
Stop the Server and Observe the Output
Start the server, then User A's client. Leave the client running, press Ctrl+C in the server terminal, wait briefly, then run node server.mjs again.
| Action | Expected output for User A |
|---|---|
| First startup | Connected, joining room → Joined room1 |
| Stop the server | Disconnected, followed by the reason |
| Server remains unavailable | Connection failed may appear repeatedly |
| Restart the server | Connected appears again → Joined room1 |
Wait until User A prints “Joined room1”, then run the previous User B client with demo-token-b and room1, automatically sending “Hello” after joining. User A should receive [User B] Hello once.
🧰 Limit Reconnection Attempts
By default, the client keeps trying. To stop after a limited number of attempts, replace the socket creation code with:
const socket = io('http://localhost:3000', {
auth: { token: 'demo-token-a' },
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5
});
| Option | Purpose |
|---|---|
| reconnectionDelay | Base initial retry delay, in milliseconds |
| reconnectionDelayMax | Maximum retry delay, in milliseconds |
| reconnectionAttempts | Maximum number of automatic reconnection attempts |
The delay increases gradually and includes randomization, so logs will not appear exactly once per second. Automatic reconnection stops if the attempt limit is reached without success. Client options
To show that retries have stopped, add this listener at the client's top level.
socket.io.on('reconnect_failed', () => {
console.log('Reconnection attempts exhausted; check the server and restart the client');
});
Here, socket.io is the client's internal object that manages connections and retries. Listen for exhausted retries on that object. After testing limited retries, remove these three options to restore the defaults. Client API
❓ Questions and Answers
Q1: Why doesn't the client reconnect after an intentional disconnection?
Calling socket.disconnect() intentionally ends the connection. The client stays disconnected until socket.connect() is called again. If authentication rejects an invalid token, correct the credentials before reconnecting as well.
Q2: Will rejoining deliver messages sent while the client was offline?
The current server broadcasts only to room members online at the time. Rejoining enables future messages; recovering earlier ones requires the server to save them and the client to retrieve them.
🧪 Exercise
Restart the server three times. Each time, wait for User A to rejoin room1, then start User B to send “Hello” and stop B after acknowledgement. User A should print exactly one new message per round. Check for duplicate listeners if it does not.
Then enable the five-attempt limit, stop the server, and wait for “Reconnection attempts exhausted”. Restart the server and observe that User A does not reconnect automatically. Restart the client to verify successful connection and room joining.
🎉 You can now verify disconnection notices, automatic reconnection, and restoration of room subscriptions.
