How to get current socket object or id with in a sails controller?

我只是一个虾纸丫 提交于 2019-12-02 07:29:14

You need to pass the req object to the method.

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

Since the request is not a socket request, you might need to do something like

  • Send back some identifier to the client once logged in.
  • Use the identifier to join a room. (One user per room. )
  • Broadcast messages to the room with the identifier whenever you need to send message to client.

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

Update:

From sails migration guide

The onConnect lifecycle callback has been deprecated. Instead, if you need to do something when a new socket is connected, send a request from the newly-connected client to do so. The purpose of onConnect was always for optimizing performance (eliminating the need to do this initial extra round-trip with the server), yet its use can lead to confusion and race conditions. If you desperately need to eliminate the server roundtrip, you can bind a handler directly on sails.io.on('connect', function (newlyConnectedSocket){}) in your bootstrap function (config/bootstrap.js). However, note that this is discouraged. Unless you're facing true production performance issues, you should use the strategy mentioned above for your "on connection" logic (i.e. send an initial request from the client after the socket connects). Socket requests are lightweight, so this doesn't add any tangible overhead to your application, and it will help make your code more predictable.

// in some controller
if (req.isSocket) {
    let handshake = req.socket.manager.handshaken[sails.sockets.getId(req)];
    if (handshake) {
        session = handshake.session;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!