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

后端 未结 1 944
借酒劲吻你
借酒劲吻你 2021-01-25 20:18

I would like to access the currently connected socket id with in a sails.js (v0.12 ) controller function. sails.sockets.getId(req.socket); is showing undefined

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 20:35

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

    0 讨论(0)
提交回复
热议问题