使用套接字 io 连接的客户端用户名列表 [英] List of connected clients username using socket io

查看:17
本文介绍了使用套接字 io 连接的客户端用户名列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 NodeJS、socketIO 和 Express 制作了一个带有不同聊天室的聊天客户端.我正在尝试显示每个房间的已连接用户的更新列表.

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')

然后做这样的事情:

users[0].username

我还能通过哪些其他方式做到这一点?

In what other ways can I do this?

已解决:
这有点重复,但解决方案在任何地方都没有写得很清楚,所以我想我把它写在这里.这是post<的解决方案/a> 来自 Andy Hin马克.还有这篇文章中的评论.

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 也有一个 get 方法,所以如果你想让所有的用户都这样做:

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

正如 alessioalex 所指出的那样,API 可能会发生变化,自己跟踪用户会更安全.您可以通过在断开连接时使用套接字 ID 来执行此操作.

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

推荐答案

有类似的问题可以帮助您解决这个问题:

There are similar questions that will help you with this:

Socket.IO - 如何获取已连接套接字/客户端的列表?

使用 socket.io 创建已连接客户端列表

我的建议是自己跟踪连接的客户端列表,因为您永远不知道 Socket.IO 的内部 API 何时会发生变化.因此,在每次连接时,将客户端添加到数组(或数据库)中,并在每次断开连接时将其删除.

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.

这篇关于使用套接字 io 连接的客户端用户名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆