A
A
ArtemAvdeyev2019-07-14 19:30:22
JavaScript
ArtemAvdeyev, 2019-07-14 19:30:22

Why is disconnect not working correctly?

Hello, I recently started learning socket.io. With them, I want to display all users who are currently online. Everything seems to be working out, but only disabling the user does not work as planned. The logic is this: when visiting the site, the user sends his login to the server, and the server writes it to the array of online users. On exit, the user's login is removed from the array of online users. But, when one user exits, all users are written out of the array. Why is this happening?
server

const users = [];

    io.on('connection', (socket) => {
        socket.on('global room', (global) => {

            socket.login = global.login;
            users.push(socket.login);

            socket.join(global.room);

            socket.emit('onlineUsers', users);
        });

        socket.on('disconnect', () => {
            users.splice(socket.login, 1);
            socket.emit('onlineUsers', users);
        })
    });

client
var socket = io();

    socket.on('connect', function(){

        var room = 'global room';
        var userLogin = $('#userLogin').val();

        socket.emit('global room', {
            room: room,
            login: userLogin
        });

        socket.on('onlineUsers', function(users){
          console.log(users);
        });
    });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ArtemAvdeyev, 2019-07-15
@ArtemAvdeyev

Changed to
And everything worked correctly

S
Stockholm Syndrome, 2019-07-14
@StockholmSyndrome

the splice method expects as the first argument the index of the array element from which to start deleting, and you pass the element itself
correctly like this:
users.splice(users.indexOf(socket.login), 1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question