Broadcast a custom message about the record with the specified id
to all sockets currently subscribed to it.
Something.message( id, data )
Or:
Something.message(id, data, req);
Argument | Type | Details | |
---|---|---|---|
1 | id |
The id of the record whose subscribers will receive this broadcast. e.g. 4 |
|
2 | data |
Arbitrary data to send to the subscribed sockets; i.e. a dictionary containing any JSON-serializable data you would like to broadcast to all sockets subscribed to this record. Must be JSON-serializable. | |
3 | req |
If provided, then the requesting socket will not receive the broadcast. |
message()
broadcasts to all sockets subscribed to the record (e.g. via .subscribe()
) and uses the model's identity as the event name. The broadcasted event data received by the subscribed sockets will be a dictionary with the following properties:
'messaged'
id
which is a .message()
on the backendIn a controller+action... Find a user by username and broadcast a message back to all of its subscribers:
User.findOne({username: 'bob'}).exec(function(err, foundUser){
if (err) return res.serverError(err);
if (!foundUser) return res.notFound();
// This message can contain anything you want!
User.message(foundUser.id, {count: 12, hairColor: 'red'});
return res.ok();
});
The endpoint will respond with a simple 200 (because of res.ok()
), but all subscribed client sockets will receive a user
event:
// e.g. in the browser...
io.socket.on('user', function (event){
console.log(event);
// => see below
});
In this case, the event
dictionary would look the same for every client socket which received the message:
{
verb: 'messaged',
id: 83,
data: {
count: 12,
hairColor: 'red'
}
}
- Be sure and check
req.isSocket === true
before passing inreq
to refer to the requesting socket. If used, the providedreq
must be from a socket request, not just any old HTTP request.