list of users socketio nodejs

Asked

Viewed 87 times

0

I’m using the following scripts below to store a list of users who are logged in to the chat I’m doing in socket.io and nodejs, but I wanted to store more than one object, in case I’m only able to store the id,Someone could give me a help on how to solve this problem. Thank you!

  • Below js file.

var users = [];
io.on("connection", function(socket){
    console.log("User connected: ",  socket.id);
    
    socket.on("user_connected", function(username){
        socket.username = username;
        users[username] = socket.id;
        io.sockets.emit("user_connected", Object.keys(users));
    });
});

  • Below index.

function enterName(){
io.emit("user_connected", idUser);
return false;
}

io.on("user_connected", function(users){
$("#lista_usuarios").empty();
$.each(users, function(indice){

opcao_usuario = ""+users[indice]+"<br />";
$("#lista_usuarios").append(opcao_usuario);
});
});

  • Very confusing your code, in the key username of the array is inserting the id, tbm did not understand why did not use a objeto instead of a array pq will have key and value, in fact if it were I would not create variable any pass the data directly on emit, thus: {id: socket.id, username: socket.username}

  • In the case "users = [];" -> are the users who log into the chat with a certain key, then I get the id in the case that is the username and compare with the user to show the list of users. Could you give me a hand tweaking that code?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.