简体   繁体   English

使用socket.io将数组从服务器发送到客户端

[英]Sending array from server to client with socket.io

I am developing a small chat app, and I would like to be able to display a list of connected users. 我正在开发一个小型聊天应用程序,并且希望能够显示已连接用户的列表。 To do so, on my server side, I have: 为此,在服务器端,我有:

var users = {};

    io.on('connection', function(socket){
        socket.on('newUser', function(pseudo) {
            socket.pseudo = pseudo;
            users[socket.pseudo] = socket;
            io.sockets.emit('newUser', pseudo);
            console.log(Object.keys(users));
        });

The console sends me back [ 'root' ] if I connect the user root. 如果我连接了用户root,控制台会将我发回[ 'root' ] And this is what I have on my client side: 这就是我在客户端的内容:

var pseudo = '#{user.username}';
socket.emit('newUser', pseudo);

    socket.on('newUser', function(pseudo) {
        $('#messageZone').append('<p><em>' + pseudo + ' just joined the conversation !</em></p>');
    });

So my question is, how can I send the full updated users array to each client when they connect themselves and display it in a div ? 所以我的问题是,当客户端相互连接并在div显示时,如何将完整的更新users数组发送给每个客户端?

Thank you for your help! 谢谢您的帮助!

If you just want to send all current connected users to all other users from the server, you could do this: 如果只想从服务器将所有当前连接的用户发送给所有其他用户,则可以执行以下操作:

io.sockets.emit('allUsers', Object.keys(users));

And, in the client to set this list into a div: 并且,在客户端中将此列表设置为div:

socket.on('allUsers', function(listOfUsers) {
    $('#allUsers').html(listOfUsers.join(", "));
});

This would get the list of keys from the users object which looks like it would be the pseudo values for each user. 这将从users对象中获取密钥列表,这看起来像是每个用户的pseudo值。 The array would turns into JSON, sent to each client. 该数组将变成JSON,发送给每个客户端。 Each socket.io client would then parse the JSON back into an array and you'd receive an array on the client which you could then put into the HTML. 然后,每个socket.io客户端都会将JSON解析回一个数组,然后您会在客户端上收到一个数组,然后可以将其放入HTML中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM