如何在sails控制器中获取当前套接字对象或id?

我想通过sails.js(v0.12)控制器函数访问当前连接的套接字id。 sails.sockets.getId(req.socket); 显示未定义,因为这不是一个套接字请求

我的目标是成功login后,将我的用户的在线状态设置在数据库中

login: function (req, res) { Util.login(req, function(){ var socketId = sails.sockets.getId(req.socket); console.log('socketId ===', socketId); // return undefined }); }, 

基本上我想访问控制器中的当前用户的套接字对象或在套接字方法on访问当前用户的会话对象

另外,我不知道如何重写我的旧sockets.onConnect处理程序

  onConnect: function(session, socket) { // Proceed only if the user is logged in if (session.me) { //console.log('test',session); User.findOne({id: session.me}).exec(function(err, user) { var socketId = sails.sockets.getId(socket); user.status = 'online'; user.ip = socket.handshake.address; user.save(function(err) { // Publish this user creation event to every socket watching the User model via User.watch() User.publishCreate(user, socket); }); // Create the session.users hash if it doesn't exist already session.users = session.users || {}; // Save this user in the session, indexed by their socket ID. // This way we can look the user up by socket ID later. session.users[socketId] = user; // Persist the session //session.save(); // Get updates about users being created User.watch(socket); // Send a message to the client with information about the new user sails.sockets.broadcast(socketId, 'user', { verb :'list', data:session.users }); }); } }, 

您需要将req对象传递给方法。

 if (req.isSocket) { let socketId = sails.sockets.getId(req); sails.log('socket id: ' + socketId); } 

由于请求不是套接字请求,因此可能需要执行类似的操作

  • 一旦login,向客户端发回一些标识符。
  • 使用标识符来join房间。 (每个房间一个用户)
  • 无论何时需要将消息发送到客户端,都可以使用标识符将消息广播到房间。

https://gist.github.com/crtr0/2896891

更新:

从帆迁移指南

onConnect生命周期callback已被弃用。 相反,如果您在连接新套接字时需要执行某些操作,请从新连接的客户端发送请求。 onConnect的目的始终是优化性能(不需要对服务器进行这种初始的额外往返),但其使用可能会导致混乱和竞争状况。 如果您迫切需要消除服务器往返,则可以在引导程序函数(config / bootstrap.js)中直接在sails.io.on('connect',function(newlyConnectedSocket){})上绑定一个处理程序。 但是请注意,这是不鼓励的。 除非你面临真正的生产性能问题,否则你应该使用上面提到的用于“连接”逻辑的策略(即在套接字连接之后发送来自客户端的初始请求)。 套接字请求是轻量级的,所以这不会为您的应用程序增加任何有形的开销,这将有助于使您的代码更具可预测性。

 // in some controller if (req.isSocket) { let handshake = req.socket.manager.handshaken[sails.sockets.getId(req)]; if (handshake) { session = handshake.session; } }