manage user status in socket.io code example

Example: how to check whether the user is online or not using socket.io

const users = {};
io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('login', function(data){
    console.log('a user ' + data.userId + ' connected');
    // saving userId to array with socket ID
    users[socket.id] = data.userId;
  });
  socket.on('disconnect', function(){
    console.log('user ' + users[socket.id] + ' disconnected');
    // remove saved socket from users object
    delete users[socket.id];
  });
});

Tags:

Misc Example