Tracking user online/offline status in sails.js

泄露秘密 提交于 2019-12-21 20:39:29

问题


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


回答1:


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!
    }
  }

}


来源:https://stackoverflow.com/questions/22035085/tracking-user-online-offline-status-in-sails-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!