是否有可能听到join和离开房间的事件?

我想做一些事情:

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

这似乎并不奏效。 可能吗?

为了说明所需的行为:

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

在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); 

需要注意的是,如果您(1)获得了一个房间中所有套接字的列表,并且(2)对它们进行了迭代,则每个套接字都会调用emit('join') ,您将获得相同的效果。 因此,您应该确保您的活动名称足够具体,以免您不小心将其排放到房间的“名称空间”之外。

如果您只想在套接字join或离开房间时发出/消耗单个事件,那么您需要自己写一个事件,因为再次,房间不是一个“事物”,而是一个“filter” 。

您可以使用本机“断开”事件。

 socket.on('disconnect', function () { io.sockets.emit('user disconnected'); }); 

我知道这个问题是旧的,但对于任何人通过谷歌search绊倒,这是我如何接近它。

即使没有join或离开房间的本地事件,join房间也是相当容易考虑的事情。

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

而对于服务器端来说

 /* 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 }); 

哪里有一点棘手是当他们断开连接,但幸运的是,在拆除房间中的sockets之前发生的disconnecting事件。 在上面的例子中,如果事件是disconnect那么房间将是空的,但是disconnecting将具有它们所属的所有房间。 对于我们的例子,你将有两个房间,套接字将成为一部分, Socket#idrandom-room

我希望这从我的研究和testing指向正确的方向别人。