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.