Reputation: 142
So I want to listen to messages that I get from sockets in my Sails.js app. How can I achieve that?
Is there something like socket.io on method?
Upvotes: 1
Views: 1166
Reputation:
There is exactly something like the socket.io on
method.
Take a look in here: http://sailsjs.org/#!/documentation/reference/websockets/resourceful-pubsub
Here's a little example.
Let's say you are using Model.message
to broadcast your messages, and are using Sails' Socket Client.
In this example, we're going to assume that:
/messageStream
User
In order to listen for messages, you must first subscribe to the context. So let's go on...
Subscribing in your controller:
User.subscribe(req.socket, { id: req.user.id }, 'message');
The first parameter is the request socket, the second one is the list of users you want to subscribe to the context(s) (in this example, only one user) and the third one is the context(s) you want to subscribe to, which in this case is only the message
context.
Listening for messages in your client:
io.socket.get('/messageStream');
io.socket.on('user', function(obj) {
if(obj.verb === 'messaged') {
console.log(obj);
// Do something fun with the message object!
}
});
The parameter in io.socket.get
is your controller's route.
The first parameter in io.socket.on
is your model's name in lowercase.
Notice that when you receive a message, the object received comes with the messaged
verb.
...And that's pretty much it.
Upvotes: 3