socket.io determine if a user is online or offline

后端 未结 2 969
死守一世寂寞
死守一世寂寞 2020-12-23 15:12

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

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


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 15:35

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

    
    

    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 object 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.

提交回复
热议问题