2014-02-26 54 views

回答

2

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

跟踪的最佳方法是使用Sails PubSub方法。如果你有一个User模型和UserControllerlogin方法,你可以不喜欢在最新帆编译:

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

} 
+0

感谢您的答复。这答案非常有趣和有用.Thanks了很多。我现在试过了。正如你所说,即使IAM没有注销,套接字也会断开连接。所以,当一个人离线时,即当一个人注销时,我也需要跟踪。 – Mahahari