socket.io determine if a user is online or offline

2020-05-15 05:08发布

问题:

We can trace if a connection is established or disconnected by this code

console.log('a user connected');
    socket.on('disconnect', function () {
        console.log('user disconnected');
    });

Well, its fine. But how can we determine what user connected or gone offline. My client is written in PHP/HTML so they have a user ID.

回答1:

If your clients have specific user IDs they need to send them to socket.io server. E.g. on client side you can do

<script>
 const socket = io();
 socket.emit('login',{userId:'YourUserID'});
</script>

And on server you will put something like

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];
  });
});

Now you can pair socket ID to your user ID and work with it.