Emitting socket.io event from Sails.JS and handling it on server using Sails.JS skeleton

前端 未结 2 1931
清酒与你
清酒与你 2021-02-01 11:14

I have a problem in understanding the concept of sending socket.io events from Sails.js client side controller and handling them in server-side controllers. First of all, I have

相关标签:
2条回答
  • 2021-02-01 11:52

    Be sure to read the SailsJS v0.11 Migration Guide before using onConnect. This has now been deprecated.

    0 讨论(0)
  • 2021-02-01 12:02

    If all you're trying to do is run a Sails controller action via sockets, then you don't need to emit anything at all. Part of Sails' charm is that it can route regular, HTTP-style requests over sockets. So if you have a controller /api/controllers/FooController.js like:

    module.exports = {
    
        bar: function (req, res) {
    
            // Note, you can check whether this was a socket request
            // with req.isSocket, and if so access the connecting
            // socket with req.socket
    
            res.json({"message": "Hello!"});
    
        }
    
    }
    

    and you include the bundled sails.io.js file in your client-side app, then you can access that action via:

    socket.get('/foo/bar', function(data) {
        // data will contain {message:"hello"}
    }
    

    Note: if you're using the newer version of sails.io.js that is included with Sails v0.10.x, it's io.socket.get.

    If you really want to catch socket events on the server, the best place to register them is in your /config/socket.js file, in the onConnect method:

    onConnect: function (socket, session) {
    
        socket.on('some_event', function(data) {
            // handle event here
        });
    
    }
    

    This is better than putting the event handlers in a controller, because any time that controller action ran it would bind the event again, and you'd see the callback being run multiple times.

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