Broadcast a message to all sockets in a room (or to a particular socket).
sails.sockets.broadcast(roomNames, data);
Or:
sails.sockets.broadcast(roomNames, eventName, data);sails.sockets.broadcast(roomNames, data, socketToOmit);sails.sockets.broadcast(roomNames, eventName, data, socketToOmit);| Argument | Type | Details | |
|---|---|---|---|
| 1 | roomNames | The name of one or more rooms to broadcast a message in (see sails.sockets.join). To broadcast to individual sockets, use their IDs as room names. | |
| 2 | eventName | Optional. The unique name of the event used by the client to identify this message. Defaults to 'message'. |
|
| 3 | data | The data to send in the message. | |
| 4 | socketToOmit | Optional. If provided, the socket belonging to the specified socket request will not receive the message. This is useful if you trigger the broadcast from a client, but don't want that client to receive the message itself (for example, sending a message to everybody else in a chat room). |
In an action, service, or arbitrary script on the server:
sails.sockets.broadcast('artsAndEntertainment', { greeting: 'Hola!' });
On the client:
io.socket.on('message', function (data){
console.log(data.greeting);
});
More examples of sails.sockets.brodcast() usage are available here, including broadcasting to multiple rooms, using a custom event name, and omitting the requesting socket.
sails.sockets.broadcast()is more or less equivalent to the functionality of.emit()and.broadcast()in Socket.io.- Every socket is automatically subscribed to a room with its ID as the name, allowing direct messaging to a socket via
sails.sockets.broadcast()- Be sure and check
req.isSocket === truebefore passing inreqassocketToOmit. For the requesting socket to be omitted, the request (req) must be from a socket request, not just any old HTTP request.datamust be JSON-serializable; i.e. it's best to use plain dictionaries/arrays, and make sure your data does not contain any circular references. If you aren't sure, build your broadcastdatamanually, or call something likerttc.dehydrate(data,true,true)on it first.