在sails.js 中跟踪用户在线/离线状态 [英] Tracking user online/offline status in sails.js

查看:41
本文介绍了在sails.js 中跟踪用户在线/离线状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在我的网络应用程序中使用sails.js 中的websockets 找出用户状态,即用户是否在线/离线.

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

请帮帮我.非常感谢

推荐答案

从 Sails v0.9.8 开始,您可以使用 中的 onConnectonDisconnect 函数config/sockets.js 以在套接字连接到系统或从系统断开连接时执行一些代码.这些函数使您可以访问会话,因此您可以使用它来跟踪用户,但请记住,仅仅因为套接字断开连接,并不意味着用户已注销!他们可以打开多个选项卡/窗口,每个选项卡/窗口都有自己的套接字,但所有这些都共享会话.

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.

跟踪的最佳方法是使用 Sails PubSub 方法.如果你有一个 User 模型和一个带有 login 方法的 UserController,你可以在最新的 Sails 版本中做一些类似的事情:

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

}

这篇关于在sails.js 中跟踪用户在线/离线状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆