Understand Socket Disconnection
A Socket.IO connection can close for several reasons.
Examples include:
- The user closes the browser tab.
- The network connection disappears.
- The server shuts down.
- A reverse proxy closes an inactive connection.
- The client explicitly disconnects.
- A transport error occurs.
The server receives the disconnect event when a socket connection closes.
The event callback provides a reason describing why the disconnection happened.
Use this event to clean up connection-specific resources and update application presence information.
Handle Disconnection
io.on('connection', (socket) => {
console.log('Connected:', socket.id);
socket.on('disconnect', (reason) => {
console.log('Disconnected:', socket.id);
console.log('Reason:', reason);
});
});Registers a disconnect listener and logs the connection identifier and disconnection reason.
Key Takeaways
Disconnections can occur for several reasons.
The disconnect event provides a reason.
Connection-specific resources should be cleaned up.