noa-dev
noa-dev

Reputation: 3641

Socket.io disconnect function not working

I am nearly done with my socket.io implementation example. The only thing thats missing is the functionality of the disconnect event.

I have tried to put it inside the io connection function, outside, everything came to my mind. Sadly the disconnect function doesn't get triggered at all.

Heres my route file code which contains said functions:

/* GET /backend */
router.get('/', function(req, res, next) {
  if (req.session && req.session.user) { // Check if session exists

  var currentUser = req.session.user[0].name; // save username according to session

    if(!req.session.user[0].io){
      req.app.get('io').on('connection', function(socket){ // Gets executed when user connects to /backend/
        req.session.user[0].io = true; // Sets the io session to true
        console.log("IO SESSION SET : "+ req.session.user[0].io +" for user " + currentUser);
      });

    if(req.session.user[0].io){
      req.app.get('io').on('disconnect', function(){
        req.session.user[0].io = false;
        console.log("IO SESSION SET : "+ req.session.user[0].io +" for user " + currentUser);
        req.app.get('io').emit('wentOffline', currentUser); // emit wentOffline to client js
      });
    }
      req.app.get('io').emit('cameOnline', currentUser); // emit function cameOnline to client js
    }
    // res.render('backend', { title: 'Backend' });
    // console.log(req.session.user[0].name);

    /*
    -------------------------
    #########################
    IF EVERYTHING FAILS - THE CODE BELOW IS THE NORMAL RENDER WITHOUT SOCKET IO
    #########################
    -------------------------
    */
    // lookup the user in the DB by pulling their email from the session
    User.getUser({ name: req.session.user.name }, function (err, user) {
      if (!user) {
        console.log("No User found");
        // if the user isn't found in the DB, reset the session info and
        // redirect the user to the login page
        // console.log(user);
        req.session.reset();
        res.redirect('/login');
      } else {
        // expose the user to the template
        res.locals.user = user;
        // render the dashboard page


        function passOnlineUsers(callback){ // Looks for All users who are online
          User.getOnlineUsers({}, function(err, res, fields){
            // console.log(res);
            if (err) throw err;
            callback(err, res);
          });
        }

        passOnlineUsers(function(err, result){
          res.render('backend', { title: 'Backend', viewer: req.session.user[0], online: result });
          // res.render('backend', { title: 'Backend', viewer: "", online: result });
        });
      }
    });
  } else {
    res.redirect('/login');
  }
});

And if its needed here is also the loaded client side file with the io code:

<script>
    var socket = io();
    // socket.emit('cameOnline', "new User");

    socket.on('cameOnline', function(name){
      console.log(name + " connected.");
      var $li = $('<li/>');
      $li.addClass(name);
      if($('#onlineUsers .'+name).length == 0){
        console.log(name + " is about to be added");
        $li.text(" "+ name);
        $('#onlineUsers').append($li);
      }else{
        console.log("no new user");
      }
      // $('#onlineUsers').append($("<span>").text(" " + name)).addClass(name);
    });

    socket.on('wentOffline', function(name){
      console.log(name +" is about to go offline");
      var toDel = $('#onlineUsers li.'+name);
      toDel.remove();
    });
    </script>

Everything except the disconnect function works fine. When a user comes online the cameOnline function gets fired and adds the user to the list in the backend.

Although when the user disconnects - nothing happens.

Any ideas ? oO

Upvotes: 1

Views: 1284

Answers (1)

Lajos Veres
Lajos Veres

Reputation: 13725

The disconnect event handler should be attached to the socket, not the main io object.

So something like this should work:

req.app.get('io').on('connection', function(socket){
    ...
    socket.on('disconnect', function(){
        ...
    });
});

(And I would verify the .emits too. I think they also have to be called on the socket object, not on the io.

Upvotes: 2

Related Questions