Is it possible to listen for join and leave events on a room?

后端 未结 4 639

I want to do something like:

var room = io.sockets.in(\'some super awesome room\');
room.on(\'join\', function () {
    /* stuff */
});
room.on(\'leave\', functi         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 14:52

    In Socket.IO, a "room" is really just a namespace, something to help you filter your giant bag of sockets down to a smaller bag of sockets. Calling io.sockets.in('room').on('something') will cause the event handler to fire for every socket in the room when the event fires. If that's what you want, something like this should do the trick:

    var room = io.sockets.in('some super awesome room');
    room.on('join', function() {
      console.log("Someone joined the room.");
    });
    room.on('leave', function() {
      console.log("Someone left the room.");
    });
    
    socket.join('some super awesome room');
    socket.broadcast.to('some super awesome room').emit('join');
    
    setTimeout(function() {
      socket.leave('some super awesome room');
      io.sockets.in('some super awesome room').emit('leave');
    }, 10 * 1000);
    

    Important to note is that you'd get the same effect if you (1) got a list of all sockets in a room and (2) iterated over them, calling emit('join') on each. Thus, you should make sure that your event name is specific enough that you won't accidentally emit it outside the "namespace" of a room.

    If you only want to emit/consume a single event when a socket joins or leaves a room, you'll need to write that yourself, as, again, a room isn't a "thing" as much as it's a "filter".

提交回复
热议问题