Handle Client Connections

Socket.IO provides a connection event that fires whenever a client successfully establishes a connection.

The callback receives a socket object representing that particular client connection.

The socket object provides methods and properties for:

  • Receiving events.
  • Sending events.
  • Joining rooms.
  • Leaving rooms.
  • Disconnecting clients.
  • Accessing connection information.

Add a connection listener to the Socket.IO server.

Important Socket Properties

socket.id

Unique connection identifier

Identifies a particular connection. It is not a permanent user identity.

socket.connected

Connection status

Indicates whether the socket is currently connected.

socket.handshake

Handshake information

Contains connection details and authentication data supplied during the handshake.

socket.rooms

Joined rooms

A Set containing the rooms joined by the socket.

Handle Connections
io.on('connection', (socket) => {
  console.log('New client connected:', socket.id);

  socket.on('disconnect', (reason) => {
    console.log('Client disconnected:', socket.id, reason);
  });
});

The connection callback executes once for each connected client. Each client receives a unique socket ID for its current connection. The disconnect callback runs when that connection closes.

Key Takeaways
  • The connection event executes for every new client.

  • Each connection has its own socket object.

  • The disconnect event helps clean up connection-specific resources.