Question

I have to find out the user status ie whether the user is online/offline using websockets in sails.js in my web application.

Please help me . Thanks a lot

Was it helpful?

Solution

Starting with Sails v0.9.8, you can use the onConnect and onDisconnect functions in config/sockets.js to execute some code whenever a socket connects or disconnects from the system. The functions give you access to the session, so you can use that to keep track of the user, but keep in mind that just because a socket disconnects, it doesn't mean the user has logged off! They could have several tabs / windows open, each of which has its own socket but all of which share the session.

The best way to keep track would be to use the Sails PubSub methods. If you have a User model and a UserController with a login method, you could do something like in the latest Sails build:

// UserController.login

login: function(req, res) {

   // Lookup the user by some credentials (probably username and password)
   User.findOne({...credentials...}).exec(function(err, user) {
     // Do your authorization--this could also be handled by Passport, etc.
     ...
     // Assuming the user is valid, subscribe the connected socket to them.
     // Note: this only works with a socket request!
     User.subscribe(req, user);
     // Save the user in the session
     req.session.user = user;

   });
}


// config/sockets.js

onConnect: function(session, socket) {

  // If a user is logged in, subscribe to them
  if (session.user) {
    User.subscribe(socket, session.user);
  }

},

onDisconnect: function(session, socket) {

  // If a user is logged in, unsubscribe from them
  if (session.user) {
    User.unsubscribe(socket, session.user);
    // If the user has no more subscribers, they're offline
    if (User.subscribers(session.user.id).length == 0) {
      console.log("User "+session.user.id+" is gone!");
      // Do something!
    }
  }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top