Hotgeart
Hotgeart

Reputation: 384

Event disconnect

I'm trying to learn nodejs with this french tutorial for a chat with nodejs https://www.youtube.com/watch?v=8jkkd2Ohte8

But I can't get the user who leave the room.

Server.js

var http = require('http');

httpServer = http.createServer(function(req, res){
    // some magic
});

httpServer.listen(1337);

var io = require('socket.io').listen(httpServer);
var users = {};

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

    var user = false;

    for(var k in users){
        socket.emit('newUser', users[k]);
    }

    socket.on('login', function(user){
        user = user;
        users[user.id] = user;
        io.sockets.emit('newUser', user);
    });

    // HERE IS THE PROBLEM
    socket.on('disconnect', function(){
        console.log('LOGOUT');
        console.log(user);
        if(!user){
            return false;
        }
        delete users[user.id];
        io.sockets.emit('logout', user)
    });
});

And my client.js

(function($){

    var socket = io.connect('http://localhost:1337');
    var rand   =  Math.floor((Math.random() * 1000) + 1);

    socket.emit('login', {
        id : rand,
        username : 'Guest' + rand
    })

    socket.on('newUser', function(user){
        $('#users').append('<li id="u'+ user.id +'"><a href="http://rencontre-ados.net/profil'+ user.id +'">'+ user.username + '</a></li>');
    });

    socket.on('logout', function(user){
        $('#users #u'+ user.id).remove();
    });

})(jQuery);

When I disconnect from the chat LOGOUT appear in my console but user is false so i can't remove the id from my list of connected users.

Upvotes: 0

Views: 125

Answers (1)

Ben
Ben

Reputation: 5074

you need to save user in users by socket.id since you have access to socket.id in the disconnect event:

socket.on('login', function(user){
    users[socket.id] = user;  // <<<<< use socket.id
    io.sockets.emit('newUser', user);
});
socket.on('disconnect', function(){ 
    var user = users[socket.id];  // <<<< use socket.id
    console.log('LOGOUT');
    console.log(user);
    io.sockets.emit('logout', user)
    delete users[socket.id];
});

Upvotes: 1

Related Questions