SocketIO Identify what user disconnected

Maybe I'm late to the party but I was stuck with something similar and found it the hard way and this may help someone.

The best way to detect if the user is disconnected is would be to first set the username in socket session.

Send the name from the client on emit

socket.emit("newUser", username);

and on server

socket.on('newUser',function (username) {
     // we store the username in the socket session for this client
     socket.username = username;
});

and when the user disconnects find that on the disconnect event

socket.on('disconnect', function () {
    var connectionMessage = socket.username + " Disconnected from Socket " + socket.id;
    console.log(connectionMessage);
  });

and you can take it from there.


var users = [];
socket.on('newUser', (username) => {
    users.push({
        id: socket.id,
        username: username
    });
});
socket.on('disconnect', () => {
     const presentUser = users.find(user => user.id == socket.id);
     users = users.filter(user => user != presentUser);
});

You could just store the id value in the parent scope, which the disconnect event handler would have access to:

io.on('connection', function(socket) {
  var userId;
  socket.on('new player', function(id, name) {
    userId = id = parseInt(id);
    // ...
  });

  socket.on('disconnect', function() {
    delete playerList[userId];
  });
};

This worked for me:

On every new connection or user who comes online generate a socket Id, add it to the user object, and add it to the array of all the users online.

const users = [];
io.on('connection', (socket) => {
const socketId = socket.id; 


socket.on('user online', (data) => {

    users.push({ ...data, socketId });
    io.emit('view user online', user);
  });

Then in the disconnect, use forEach to loop through each object in the array, then use for to loop through and delete each key in the object:

 socket.on('disconnect', () => {
    users.forEach((user) => {
      if (user.socketId === socket.id) {
        for (const key in user) {
          delete user[key];
        }
      }
        });

        logger(`A user has disconnected`);
      });
      });
});

Tweak to the way you want.