是否有可能在房间里听取加入和离开事件?

lak*_*nen 12 javascript node.js socket.io

我想做的事情如下:

var room = io.sockets.in('some super awesome room');
room.on('join', function () {
    /* stuff */
});
room.on('leave', function () {
    /* stuff */
});
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用.可能吗?

为了说明所需的行为:

io.sockets.on('connection', function (socket) {
    socket.join('some super awesome room'); // should fire the above 'join' event
});
Run Code Online (Sandbox Code Playgroud)

Mic*_*ley 15

在Socket.IO中,"房间"实际上只是一个命名空间,可帮助您将巨大的插座袋过滤到较小的插座袋中.当事件触发时,调用io.sockets.in('room').on('something')将导致事件处理程序为房间中的每个套接字触发.如果这就是你想要的东西,这样的东西应该可以解决问题:

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);
Run Code Online (Sandbox Code Playgroud)

需要注意的重要一点是,如果您(1)获得一个房间中所有套接字的列表,并且(2)迭代它们,则调用emit('join')每个套接字,您将获得相同的效果.因此,您应确保您的事件名称足够具体,以免意外地将其发送到房间的"命名空间"之外.

如果你只是想发出/消耗在套接字加入或离开房间时,你需要编写自己,因为,再一次,一个房间是不是"东西"一样,因为它是一个"过滤器" .

  • "房间不是"事物",而是"过滤器"` - 这就是我所担心的(我希望socket.io有更好的文档).我想我必须写自己的房间版本......谢谢! (3认同)

Bla*_*ake 5

我知道这个问题很老,但对于通过谷歌搜索偶然发现这个问题的任何人,这就是我接近它的方式。

加入房间是很容易解释的事情,即使没有用于加入或离开房间的本地事件。

/* client.js */
var socket = io();
socket.on('connect', function () {
    // Join a room
    socket.emit('joinRoom', "random-room");
});
Run Code Online (Sandbox Code Playgroud)

而对于服务器端

/* server.js */
// This will have the socket join the room and then broadcast 
// to all sockets in the room that someone has joined
socket.on("joinRoom", function (roomName) {
    socket.join(roomName);
    io.sockets.in(roomName).emit('message','Someone joined the room');
}

// This will have the rooms the current socket is a member of
// the "disconnect" event is after tear-down, so socket.rooms would already be empty
// so we're using disconnecting, which is before tear-down of sockets
socket.on("disconnecting", function () {
    var rooms = socket.rooms;
    console.log(rooms);
    // You can loop through your rooms and emit an action here of leaving
});
Run Code Online (Sandbox Code Playgroud)

当它们断开连接时变得有点棘手,但幸运的disconnecting是添加了一个事件,该事件发生在拆除房间内的插座之前。在上面的示例中,如果事件是,disconnect那么房间将是空的,但disconnecting将拥有它们所属的所有房间。对于我们的示例,您将有两个房间作为插座的一部分,Socket#idrandom-room

我希望这能从我的研究和测试中为其他人指明正确的方向。