node.js 使用套接字 io 连接的客户端用户名列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8788790/
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
List of connected clients username using socket io
提问by kimpettersen
I've made a chat client with different chat rooms in NodeJS, socketIO and Express. I am trying to display an updated list over connected users for each room.
我在 NodeJS、socketIO 和 Express 中制作了一个带有不同聊天室的聊天客户端。我正在尝试显示每个房间的已连接用户的更新列表。
Is there a way to connect a username to an object so I could see all the usernames when I do:
有没有办法将用户名连接到一个对象,这样我就可以在执行以下操作时看到所有用户名:
var users = io.sockets.clients('room')
and then do something like this:
然后做这样的事情:
users[0].username
In what other ways can I do this?
我还可以通过哪些其他方式做到这一点?
Solved:This is sort of a duplicate, but the solution is not written out very clearly anywhere so I'd thought I write it down here. This is the solution of the postby Andy Hinwich was answered by mak. And also the comments in this post.
已解决:这有点重复,但解决方案在任何地方都没有写得很清楚,所以我想我把它写在这里。这是的解决方案后由安迪轩至极被回答麦。还有这篇文章中的评论。
Just to make things a bit clearer. If you want to store anything on a socket object you can do this:
只是为了让事情更清楚一点。如果你想在套接字对象上存储任何东西,你可以这样做:
socket.set('nickname', 'Guest');
sockets also has a get method, so if you want all of the users do:
sockets 也有一个 get 方法,所以如果你希望所有用户都这样做:
for (var socketId in io.sockets.sockets) {
io.sockets.sockets[socketId].get('nickname', function(err, nickname) {
console.log(nickname);
});
}
As alessioalexpointed out, the API might change and it is safer to keep track of user by yourself. You can do so this by using the socket id on disconnect.
正如alessioalex指出的那样,API 可能会发生变化,并且自己跟踪用户会更安全。您可以通过在断开连接时使用套接字 id 来做到这一点。
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected');
//remove user from db
}
});
回答by alessioalex
There are similar questions that will help you with this:
有类似的问题可以帮助您解决这个问题:
Socket.IO - how do I get a list of connected sockets/clients?
Create a list of Connected Clients using socket.io
My advice is to keep track yourself of the list of connected clients, because you never know when the internal API of Socket.IO may change. So on each connect add the client to an array (or to the database) and on each disconnect remove him.
我的建议是自己跟踪已连接客户端的列表,因为您永远不知道 Socket.IO 的内部 API 何时会发生变化。因此,在每次连接时,将客户端添加到一个数组(或数据库)中,并在每次断开连接时将其删除。

