Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Connections and Events

The Socket.IO Connection Lifecycle

Follow a socket from connect to disconnect. Learn the lifecycle events on server and client, every disconnect reason, the socket.connected flag, cleanup patterns and common mistakes.

Every Socket.IO connection has a beginning, a middle and an end, and your code should handle all three. Setting up per-user state when a socket connects is easy; remembering to clean it up when the socket leaves is what separates a stable server from one that slowly leaks memory and shows ghost users. This lesson maps the whole lifecycle on both sides.

Lifecycle events at a glance

On the server, a socket (one per client per namespace) emits:

  • disconnecting: the socket is about to leave; socket.rooms still contains its rooms.
  • disconnect: it is gone; the argument is the reason (a string).

The connection event happens on the namespace (io.on('connection', ...)), not on the socket.

On the client, the socket emits:

  • connect: connected (also fired after every successful reconnection).
  • connect_error: the connection attempt failed (server unreachable, or a middleware rejected it).
  • disconnect: connection lost or closed; argument is the reason.

The client's socket.io property is the Manager, which handles the underlying connection and emits reconnection events such as reconnect_attempt, reconnect, reconnect_error and reconnect_failed.

stateDiagram-v2
    [*] --> Connecting
    Connecting --> Connected: connect
    Connecting --> Connecting: connect_error, retry
    Connected --> Disconnected: disconnect
    Disconnected --> Connecting: automatic reconnect
    Disconnected --> [*]: manual disconnect

After an unexpected disconnect the client goes back to Connecting by itself; after you call socket.disconnect() it stays down.

Watching the lifecycle

The stand-in below logs every stage. It fires disconnecting before the socket leaves its rooms, so you can see that socket.rooms is still populated at that moment and empty afterwards.

Node.js Logging the full lifecycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Disconnect reasons

The reason tells you who ended the connection and why. On the server:

Reason Meaning
client namespace disconnect The client called socket.disconnect().
server namespace disconnect The server called socket.disconnect().
transport close The connection was lost (tab closed, network gone).
transport error The connection hit an error.
ping timeout The client did not answer a heartbeat in time.
server shutting down The server is closing (io.close()).
parse error The server received an invalid packet.

On the client the same event uses slightly different texts: io server disconnect (the server kicked you out, and the client will not reconnect on its own), io client disconnect (you did it), ping timeout, transport close, transport error.

The important practical rule: for io server disconnect the client must call socket.connect() manually if it wants back in; for the other loss reasons it reconnects automatically (read-only snippet):

JavaScript
socket.on('disconnect', (reason) => {
  if (reason === 'io server disconnect') {
    socket.connect(); // the server refused us, so retry manually
  }
  // otherwise the Manager reconnects by itself
});

Do not call socket.connect() unconditionally on every disconnect. When the reason is something other than io server disconnect, reconnection is already scheduled, and you would create duplicate attempts.

Cleanup: tracking online users

The classic use of disconnect is removing state added on connection. Here a presence map is updated on both events. Pay attention to the guard that only announces "offline" when a user's last tab closes, which is realistic because one person often has several sockets.

Node.js Presence with several tabs per user

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Counting connections instead of using a simple Set of names is what makes the multi-tab case correct.

Detecting a dead connection

A closed browser tab sends a proper close frame, but a phone that loses signal does not. The server only learns after pingInterval + pingTimeout (45 seconds with the defaults) that the client is gone, and then fires disconnect with ping timeout. If you show "online" badges, tune those two options to balance speed against false alarms on slow networks. Also remember that a server restart disconnects everyone at once; clients see transport close and reconnect, often all at the same moment, so keep your connection handler fast.

Common mistakes

  • Registering socket.on handlers inside another handler on every event. Handlers pile up and run multiple times. Register each handler once per socket.
  • Reading socket.rooms in disconnect. It is already empty there; use disconnecting instead.
  • Treating connect as "first connection". It also fires after reconnects, so if you register listeners inside it on the client they are duplicated. Register them once outside, or use socket.on before connecting.
  • Forgetting cleanup for timers, intervals and database subscriptions created per socket. Clear them in disconnect.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where is socket.rooms still populated, so you can notify the rooms a user is leaving?

    disconnecting fires before the socket leaves its rooms; by disconnect they are empty.
  2. 2. The client receives the reason 'io server disconnect'. What happens next?

    When the server deliberately closes the socket, automatic reconnection is not attempted.
  3. 3. A user opens three tabs and closes one. Which structure lets you correctly say they are still online?

    Counting sockets per user means the user only goes offline when the count reaches zero.
  4. 4. Which event fires on the client both on the first connection and after every reconnection?

    connect is emitted each time the socket becomes connected; connection is a server-side namespace event.

Summary

  • Servers see connection (on the namespace), disconnecting and disconnect; clients see connect, connect_error and disconnect.
  • The disconnect reason says who closed the connection and why; io server disconnect needs a manual socket.connect().
  • Use disconnecting to read the rooms; use disconnect for cleanup.
  • Count sockets per user for correct presence, and clear per-socket timers and subscriptions.
  • Dead connections are found by heartbeats after pingInterval + pingTimeout.

Next: Emitting and Listening to Events