使用套接字io的已连接客户端用户名列表

使用套接字io的已连接客户端用户名列表

本文介绍了使用套接字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?

已解决:
这有点重复,但是解决方案在任何地方都不是很清楚地写出来,所以我想我会在这里写下来.这是帖子安迪·辛(.还有这篇文章中的评论.

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的已连接客户端用户名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:30