我必须找到用户状态,即用户是否在我的网络应用程序中使用sails.js中的websockets进行在线/离线。
请帮帮我。非常感谢
答案 0 :(得分:2)
从Sails v0.9.8开始,您可以使用onConnect
中的onDisconnect
和config/sockets.js
函数在套接字连接或断开系统时执行某些代码。这些函数允许您访问会话,因此您可以使用它来跟踪用户,但请记住,仅仅因为套接字断开连接,并不意味着用户已注销!他们可以打开几个标签/窗口,每个标签/窗口都有自己的套接字,但所有标签都共享会话。
保持跟踪的最佳方法是使用Sails PubSub方法。如果您拥有User
模型和UserController
并使用login
方法,则可以执行类似最新Sails构建的操作:
// 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!
}
}
}