node.js Socket IO Rooms:获取特定房间的客户端列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18093638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket IO Rooms: Get list of clients in specific room
提问by Taurian
I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.
我正在尝试显示特定房间中的客户列表。我只想显示他们的用户名,而不是他们的套接字 ID。
This where I'm at:
这是我所在的位置:
socket.set('nickname', "Earl");
socket.join('chatroom1');
console.log('User joined chat room 1);
var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
console.log('Username: ' + roster[i]);
}
Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.
没有运气让它列出套接字ID或任何东西。但是希望它返回昵称。
采纳答案by Jacob Squires
Just a few things.
只是一些事情。
when you have the
socketyou can then set the properties like:socket.nickname = 'Earl';later to use the save property for example in a console log:console.log(socket.nickname);you where missing a closing quote (') in your:
console.log('User joined chat room 1);Im not entirely sure about your loop.
当您拥有后,
socket您可以设置如下属性:socket.nickname = 'Earl';稍后在控制台日志中使用 save 属性:console.log(socket.nickname);您在以下内容中缺少结束语('):
console.log('User joined chat room 1);我不完全确定你的循环。
Below is the amended code should help you out a bit, also be aware the loop i am using below is asynchronous and this may effect how you handle data transfers.
下面是修改后的代码应该对您有所帮助,还要注意我在下面使用的循环是异步的,这可能会影响您处理数据传输的方式。
socket.nickname = 'Earl';
socket.join('chatroom1');
console.log('User joined chat room 1');
var roster = io.sockets.clients('chatroom1');
roster.forEach(function(client) {
console.log('Username: ' + client.nickname);
});
to help you out more i would need to see all your code as this does not give me context.
为了帮助你更多,我需要查看你所有的代码,因为这没有给我上下文。
回答by Sony Mathew
For people using socket.IO versions 1.0 or greater the above answer may not work.Please refer the following answer for doing so. Get list of all clients in specific room
对于使用 socket.IO 1.0 或更高版本的人,上述答案可能不起作用。请参考以下答案。 获取特定房间所有客户的列表
Code to update socket object for all clients in a room
为房间中的所有客户端更新套接字对象的代码
var clients = io.sockets.adapter.rooms['Room Name'].sockets;
//to get the number of clients
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;
for (var clientId in clients ) {
//this is the socket of each client in the room.
var clientSocket = io.sockets.connected[clientId];
//you can do whatever you need with this
clientSocket.emit('new event', "Updates");
}
回答by Vivek Doshi
回答by Qiulang
All the answers above and the one here socket.io get rooms which socket is currently inor here Socket.IO - how do I get a list of connected sockets/clients?were either incorrect or incomplete if you use 2.0.
上面的所有答案和这里的一个socket.io 获取当前套接字所在的房间或此处的Socket.IO - 如何获取已连接套接字/客户端的列表?如果您使用 2.0.0,要么不正确要么不完整。
- In 2.0,
io.sockets.managerandio.sockets.clientsdon't exist anymore. Without using namespace, the following 3 parameters can all get sockets in a specific room.
socket.adapter.rooms;io.sockets.adapter.rooms;io.sockets.adapter.sids; // the socket.id arrayWith namespace (I used "cs" here),
io.sockets.adapter.roomswill give a quite confusing result and the resultsocket.adapter.roomsgives is correct:
- 在2.0中,
io.sockets.manager并且io.sockets.clients不存在了。 在不使用namespace的情况下,以下3个参数都可以获取特定房间的socket。
socket.adapter.rooms;io.sockets.adapter.rooms;io.sockets.adapter.sids; // the socket.id array使用命名空间(我在这里使用了“cs”),
io.sockets.adapter.rooms会给出一个非常令人困惑的结果,并且socket.adapter.rooms给出的结果是正确的:
/* socket.adapter.rooms give: */
{
"/cs#v561bgPlss6ELZIZAAAB": {
"sockets": {
"/cs#v561bgPlss6ELZIZAAAB": true
},
"length": 1
},
"a room xxx": {"sockets": {
"/cs#v561bgPlss6ELZIZAAAB": true
},
"length": 1
}
}
/* io.sockets.adapter.rooms give: a sid without namespace*/
{
"v561bgPlss6ELZIZAAAB": {
"sockets": {
"v561bgPlss6ELZIZAAAB": true
}, "length": 1
}
}
Note: the default room is this: "Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id."
注意:默认的房间是这样的:“ Socket.IO 中的每个 Socket 都由一个随机的、不可猜测的、唯一的标识符 Socket#id 标识。为了您的方便,每个套接字都会自动加入一个由这个 id 标识的房间。”
I only tried memory adapter so far, have not tried redis-adapter.
我目前只试过内存适配器,还没有试过 redis-adapter。
回答by Ezzat
For Socket.io greater than v1.0 and node v6.0+ use the following code:
对于大于 v1.0 的 Socket.io 和节点 v6.0+ 使用以下代码:
function getSockets(room) { // will return all sockets with room name
return Object.entries(io.sockets.adapter.rooms[room] === undefined ?
{} : io.sockets.adapter.rooms[room].sockets )
.filter(([id, status]) => status) // get only status = true sockets
.map(([id]) => io.sockets.connected[id])
}
If you want to emit something to them , use this :
如果你想向他们发出一些东西,使用这个:
getSockets('room name').forEach(socket => socket.emit('event name', data))
回答by Isaac Pak
socket.io ^2.2.0
socket.io ^2.2.0
const socket = io(url)
socket.on('connection', client => {
socket.of('/').in("some_room_name").clients((err, clients) => {
console.log(clients) // an array of socket ids
})
})
回答by Peter Moses
I just logged all sockets in a room to the console, you can do whatever you like with them...
我刚刚将房间中的所有套接字都记录到了控制台,您可以对它们做任何想做的事情......
const socketsInRoom = io.adapter.rooms[room_name];
/*Collect all participants in room*/
for(let participant in socketsInRoom){
for(let socketId in socketsInRoom[participant]){
console.log(socketId)
}
}
回答by Jeet
You can create an array object of user collection as
您可以创建用户集合的数组对象作为
var users = {};
then on server side you can add it as new user when you connect
然后在服务器端,您可以在连接时将其添加为新用户
socket.on('new-user', function (username) {
users[username] = username;
});
while displaying the users, you can loop the "users" object
在显示用户时,您可以循环“用户”对象
On Client side
在客户端
var socket = io.connect();
socket.on('connect', function () {
socket.emit('new-user', 'username');
});

