Skip to content

Instantly share code, notes, and snippets.

@mikermcneil
Last active October 5, 2019 05:23
Show Gist options
  • Save mikermcneil/0a4d05750768a99b4fcb to your computer and use it in GitHub Desktop.
Save mikermcneil/0a4d05750768a99b4fcb to your computer and use it in GitHub Desktop.
Examples of broadcasting to a room or emitting to a single socket in your Sails app using sails.sockets.broadcast().

How to use sails.sockets.broadcast()

Linked from: http://sailsjs.org/documentation/reference/web-sockets/sails-sockets/broadcast

Basic usage

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);
});

With multiple rooms

In an action, service, or arbitrary script on the server:

sails.sockets.broadcast(['artsAndEntertainment', 'currentEvents'], { greeting: 'Hola!' });

Client-side usage is exactly the same regardless which rooms are specified:

io.socket.on('message', function (data){
  console.log(data.greeting);
});

Remember that the event name is purely for identifying this message on the client; whereas room names are not visible on the client at all, and instead control which client sockets receive the message.

With a custom event name

In an action, service, or arbitrary script on the server:

sails.sockets.broadcast('artsAndEntertainment', 'foo', { greeting: 'Hola!' });

On the client:

io.socket.on('foo', function (data){
  console.log(data.greeting);
});

Omitting the requesting socket

If req is passed in as the last argument, the requesting socket will not receive the broadcasted message:

if (req.isSocket) {
  sails.sockets.broadcast('artsAndEntertainment', {
    greeting: 'Hola!'
  }, req);
}
@pSnehanshu
Copy link

@jc5826, how would you add the routes? And what does io.socket.get actually does. Why should it send a HTTP GET request?

@vishnumishra
Copy link

vishnumishra commented Jun 26, 2019

Thanks, @jc5826, you are the life saver :)

@sailsjs Please give the full info in the documentation.

@kevgathuku
Copy link

kevgathuku commented Oct 3, 2019

Thanks @jc5826. Really helpful info, and it helped me resolve a similar issue I was facing as well 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment