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
Unique connection identifier
Identifies a particular connection. It is not a permanent user identity.
Connection status
Indicates whether the socket is currently connected.
Handshake information
Contains connection details and authentication data supplied during the handshake.
Joined rooms
A Set containing the rooms joined by the socket.
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.
The connection event executes for every new client.
Each connection has its own socket object.
The disconnect event helps clean up connection-specific resources.