Alkatell
Alkatell

Reputation: 45

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. 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?

Thank you for your help!

Upvotes: 0

Views: 2915

Answers (1)

jfriend00
jfriend00

Reputation: 707466

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:

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. The array would turns into JSON, sent to each client. 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.

Upvotes: 2

Related Questions