nehalist
nehalist

Reputation: 1496

Handle disconnect / logout events

After connecting the client subscribes to a specific room which contains all connected users:

io.socket.get('/connection/subscribe', function(data, jwr) {
  io.socket.on('user_connected', function(user) { console.log('new bro connected'); });
});

At the moment I'm just storing user ids in the memory. Therefor I use a single variable,

var connectionIDs = [];

/*...*/
subscribe: function(req, res) {
    if(typeof req.user !== 'undefined') {
        sails.sockets.join(req.socket, 'users_online');

        User.find(req.user.id).exec(function(err, user) {
            if(connectionIDs.indexOf(user[0].id) == -1) {
                connectionIDs.push(user[0].id);
            }
            sails.sockets.broadcast('users_online', 'user_connected', user);
        });

        return res.ok();
    }
},

Everything works fine so far, my only problem is handling disconnect or logout events. After closing the window, logging out or similar I need to unsubsribe from the users_online room.

Already tried

io.socket.on('disconnect', function() { io.socket.post('/disconnect', function() { }));

but sadly the request is never sent. How to handle the disconnect event properly?

Upvotes: 1

Views: 2052

Answers (1)

Mi Ke Bu
Mi Ke Bu

Reputation: 224

May be this example helps you: http://socket.io/docs/#sending-and-receiving-events

Disconnect will fired from the inside of .on('connection'). So you can detect disconnecting on server-side and client-side of your project.

Upvotes: 1

Related Questions