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 downloaded the SailsJS project skeleton using npm and the structure as follows:
Project:
api
--adapters
--controllers
----server_userController.js
--models
--polices
--services
assets
--[styles, views, images, bower_components, and etc]
--js
----controllers
------userController.js
----app.js
----sails.io.js
----socket.io.js
config
node_modules
views
I wrote the following in "assets/js/controllers/server_userController.js":
socket.emit('getUser', {
_id: 10
});
Now, how to specify which server-side controller is responsible for handling this event, and how? I want this event to be received in "api/controllers/server_userController.js". So, something like this will be in the controller:
module.exports = {
//Handling socket request here
//Emitting socket request
};
Thanks in advance
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.
Be sure to read the SailsJS v0.11 Migration Guide before using onConnect. This has now been deprecated.