Problems when ordering an array in javascript and a chat that I am creating

2

I'm creating a chat with sockets on nodejs that say it's very good. Then I create an array:

let nicknames = [];

that will save the names of users so that later the frontend will be in charge of showing them in a list. That works perfect for me.

So, I have an event called connection that detects when a user connects to the chat and adds it to the list:

//Cuando un usuario se conecta y el socket escucha
  io.on("connection", socket => {
    socket.on('new user', (data, cb) => {
        console.log("Se conecto "+data);
        if (nicknames.indexOf(data) != -1) {
            cb(false);
        } else {
            cb(true);
            socket.nickname = data;
            nicknames.push(socket.nickname);
        nicknames = nicknames.sort();
        updateNicknames();
        io.sockets.emit("nad", socket.nickname);
      }
    });

Until then everything is fine again, even the .sort () method tells me the users in alphabetical order as it should be. And the function updateNicknames (); is the one in charge of sending the users ordered to the frontend:

function updateNicknames() {
        io.sockets.emit('usernames', nicknames);
    }

so that it shows them in the list in the following way:

socket.on('usernames', data =>{
    let html = '';
    for (let i = 0; i < data.length; i++) {
      html += '<p><i class="fas fa-user"></i> ${data[i]} </p>';
    }
    $users.html(html);
  })

The problem is when I want a user to be disconnected, the last one that came out is always disconnected, regardless of the user that actually disconnects:

socket.on('disconnect', data => {
      if(!socket.nickname) return;
      io.sockets.emit("nod", socket.nickname);

      nicknames.splice(nicknames.indexOf(socket.nickanme), 1);
      updateNicknames();

    });

This line is the one that disconnects the user and then the updateNicknames () is again responsible for sending the list ordered to the frontend.

nicknames.splice(nicknames.indexOf(socket.nickanme), 1);

I do not know why the user I want is not disconnected.

    
asked by Diesan Romero 23.07.2018 в 05:24
source

1 answer

1

I think this is what you need, identify which socket is at the moment of deletion. When the user enters the user's data is assigned with the key socket.id (nicknames [socket.id] = data)

When the user is disconnected for any reason he removes the object of the array by the allocated socket (delete nicknames [socket.id];)

socket.on('new user', (data, cb) => {
  nicknames[socket.id] = data
}

socket.on('disconnect', function () {
  delete nicknames[socket.id];
}
    
answered by 24.07.2018 / 16:42
source