socket io disconnect socket code example

Example 1: socket.io do sockets leave rooms on disconnect

/* Upon disconnection, sockets leave all the channels they were part of 
automatically, and no special teardown is needed on your part.

You can fetch the rooms the Socket was in by listening to the 
disconnecting event: */

io.on('connection', socket => {
  socket.on('disconnecting', () => {
    console.log(socket.rooms); // the Set contains at least the socket ID
  });

  socket.on('disconnect', () => {
    // socket.rooms.size === 0
  });
});

Example 2: socket.io reconnect example

io.connect('http://localhost', {
  'reconnection': true,
  'reconnectionDelay': 500,
  'reconnectionAttempts': 10
});

Example 3: socket io query

// Client side
const socket = io({
  query: { token: 'cde' }
});

// Server side
io.on('connection', (socket) => {
  let token = socket.handshake.query.token;
  
  // Do something...
});