我想静静地从房间中删除所有用户,有效地删除该房间.这个想法是将来可能再次创建另一个具有相同名称的房间,但我希望它创建为空(没有前一个房间的监听器).
我对自己管理房间状态不感兴趣,但很好奇,好像我可以利用socket.io内部来做这件事.这可能吗?(另见这个问题)
Den*_*ret 16
那是你要的吗 ?
io.sockets.clients(someRoom).forEach(function(s){
s.leave(someRoom);
});
Run Code Online (Sandbox Code Playgroud)
小智 8
如果您使用的是 socket io v4 或更高版本,您可以使用以下命令:
io.in("room1").socketsLeave("room1");
//all the clients in room1 will leave romm1
//hence deleting the room automatically
//as there are no more active users in it
Run Code Online (Sandbox Code Playgroud)
有关此问题的最新答案,每个想要移走房间的人都可以使用Namespace.clients(cb)。该cb回调将收到错误对象作为第一个参数(null如果无差错)和作为第二个参数插座ID的列表。
它应该可以正常使用socket.io v2.1.0,不确定哪个版本是最早的兼容版本。
io.of('/').in('chat').clients((error, socketIds) => {
if (error) throw error;
socketIds.forEach(socketId => io.sockets.sockets[socketId].leave('chat'));
});
Run Code Online (Sandbox Code Playgroud)
@ 请
参阅https://github.com/socketio/socket.io/issues/3042 @ 请参阅https://socket.io/docs/server-api/#namespace-clients-callback
另外,值得一提的是...
断开连接时,套接字会自动保留它们所属的所有通道,并且您无需进行特殊拆卸。
https://socket.io/docs/rooms-and-namespaces/(断开连接)