Friday, 28 April 2017

Socket browser refresh drops other sockets on server

I am working on the socket.io tutorial. I am noticing that when a connected socket refreshes their browser, other connected users are being affected. Is there anything I am doing wrong that is causing other users to be disconnected on a refresh?

SERVER

io.sockets.on('connection', function(socket){

    socket.on('add user', function(data){
    socket.userName = data.user;
    users.push(data);
    socket.room = 'Lobby';
    socket.join('Lobby');
    io.sockets.in('Lobby').emit('update list', {
        users: users,
        user: data.user,
        room: socket.room
    });
});


socket.on('disconnect', function(){
    var du = users.indexOf(socket);
    users.splice(du, 1);
    io.sockets.emit('update list', {
        users: users
    });
});

});

CLIENT

$(loginButton).on('click', function(e){
       e.preventDefault();
       if(lName.val().length <= 0){
           return;
       }else{
           socket.userName = lName.val();
           socket.emit('add user', {
               user: socket.userName
           });
           $(loginScreen).css({'visibility':'hidden','display':'none'});
           $(app).css({'visibility':'visible','display':'initial'});
       }
   });

   $(guestButton).on('click', function(e){
       e.preventDefault();
       socket.userName = getName();
       socket.emit('add user', {
           user: socket.userName
       });
       $(loginScreen).css({'visibility':'hidden','display':'none'});
       $(app).css({'visibility':'visible','display':'initial'});
   });

   $(submitMessage).on('click', function(e){
       e.preventDefault();
       if(message.val().length > 0){
           socket.emit('new message', {
                message: message.val(),
                room: socket.room
            });
       }else{
           return;
       }
   });

socket.on('update list', function(data){
   $(users).html('');
   $(room).html('');
   var ult = '';
   var un = socket.userName;

   for(var u = 0; u < data.users.length; u++){

       var uun = data.users[u].user;
       if(un !== uun){
           ult = ult + '<div class="user">'+ data.users[u].user +'</div>';
       }else{
           ult = ult + '<div class="user personal">'+ data.users[u].user +'</div>';
       }
   }
   $(users).html(ult);
   $(room).html(data.room);

});



via Ryan Russell

No comments:

Post a Comment