Socket.io: How to correctly join and leave rooms

后端 未结 2 1319
借酒劲吻你
借酒劲吻你 2020-12-19 02:08

I\'m trying to learn Socket.io by building a set of dynamically created chatrooms that emit \'connected\' and \'disconnected\' messages when users enter and leave. After loo

相关标签:
2条回答
  • 2020-12-19 02:34

    Socket.IO : recently released v2.0.3

    Regarding joining / leaving rooms [read the docs.]

    To join a room is as simple as socket.join('roomName')

    //:JOIN:Client Supplied Room
    socket.on('subscribe',function(room){  
      try{
        console.log('[socket]','join room :',room)
        socket.join(room);
        socket.to(room).emit('user joined', socket.id);
      }catch(e){
        console.log('[error]','join room :',e);
        socket.emit('error','couldnt perform requested action');
      }
    })
    

    and to leave a room, simple as socket.leave('roomName'); :

    //:LEAVE:Client Supplied Room
    socket.on('unsubscribe',function(room){  
      try{
        console.log('[socket]','leave room :', room);
        socket.leave(room);
        socket.to(room).emit('user left', socket.id);
      }catch(e){
        console.log('[error]','leave room :', e);
        socket.emit('error','couldnt perform requested action');
      }
    })
    

    Informing the room that a room user is disconnecting

    Not able to get the list of rooms the client is currently in on disconnect event

    Has been fixed (Add a 'disconnecting' event to access to socket.rooms upon disconnection)

     socket.on('disconnect', function(){(
        /*
          socket.rooms is empty here 
          leaveAll() has already been called
        */
     });
     socket.on('disconnecting', function(){
       // socket.rooms should isn't empty here 
       var rooms = socket.rooms.slice();
       /*
         here you can iterate over the rooms and emit to each
         of those rooms where the disconnecting user was. 
       */
     });
    

    Now to send to a specific room :

    // sending to all clients in 'roomName' room except sender
      socket.to('roomName').emit('event', 'content');
    

    Socket.IO Emit Cheatsheet

    0 讨论(0)
  • 2020-12-19 02:47

    This is how I inform users of a "disconnecting user"

    socket.on('disconnecting', function(){
            console.log("disconnecting.. ", socket.id)
            notifyFriendOfDisconnect(socket)
        });
    
    function notifyFriendOfDisconnect(socket){
        var rooms = Object.keys(socket.rooms);
        rooms.forEach(function(room){
            socket.to(room).emit('connection left', socket.id + ' has left');
        });
    }
    
    0 讨论(0)
提交回复
热议问题