使用套接字 io 连接的客户端用户名列表
我用 NodeJS、socketIO 和 Express 制作了一个带有不同聊天室的聊天客户端。我正在尝试显示每个房间的已连接用户的更新列表。
有没有一种方法可以将用户名连接到对象,以便我可以在执行以下操作时看到所有用户名:
var users = io.sockets.clients('room')
然后执行如下操作:
users[0].username
我还可以通过哪些其他方式执行此操作?
已解决:
这有点重复,但解决方案在任何地方都没有写得很清楚,所以我想我把它写在这里。这是帖子<的解决方案/a> 由 Andy Hin 回答,马克。还有这篇文章中的评论。
只是为了让事情变得更清楚一些。如果你想在套接字对象上存储任何内容,你可以这样做:
socket.set('nickname', 'Guest');
套接字也有一个 get 方法,所以如果你希望所有用户都这样做:
for (var socketId in io.sockets.sockets) {
io.sockets.sockets[socketId].get('nickname', function(err, nickname) {
console.log(nickname);
});
}
如 alessioalex指出,API可能会改变,自己跟踪用户会更安全。您可以通过在断开连接时使用套接字 ID 来实现此目的。
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected');
//remove user from db
}
});
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.
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 post by Andy Hin which 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:
for (var socketId in io.sockets.sockets) {
io.sockets.sockets[socketId].get('nickname', function(err, nickname) {
console.log(nickname);
});
}
As alessioalex pointed 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.
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected');
//remove user from db
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有类似的问题可以帮助您解决此问题:
Socket.IO - 如何获取已连接套接字/客户端的列表?
使用socket.io创建连接的客户端列表
我的建议是自己跟踪已连接客户端的列表,因为您永远不知道 Socket.IO 的内部 API 何时会发生变化。因此,在每次连接时将客户端添加到数组(或数据库)中,并在每次断开连接时将其删除。
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.
在 [email protected] 中,您可以使用:
In [email protected] you can use: