5

I'm attempting to set up a system with sails.js to have the server broadcast messages to a set of clients. Basically:

  1. A client in Group A sends an AJAX request to the server.
  2. The server processes the request and sends a message through socket to all clients of Group B.
  3. The clients of Group B receive the message through the socket and display something.

According to the socket.io documentation, I should be able to have the clients in Group B join a "room", and then have the server broadcast to that specific room, but on the client side, the preexisting "socket" doesn't have the method "socket.join('room')". So, I tried just sending a unique event to all clients:

socket.on("connect", function(){
  console.log("Client Connected");
});

socket.on("my_event", function(data){
  console.log("my_event received");
});

This works fine by doing "sails.io.sockets.emit("my_event", {...})" on the server side, but isn't this sending the event to every single client? I could make the event name unique, something like "my_event_000" with an ID to specify the group, but that would still be sending events to every client unnecessarily.

Should I be using "rooms"? And if so, how?

mezzanine.ak
  • 53
  • 1
  • 1
  • 4

1 Answers1

4

The Sails way to do this would be to have a model backing your "Groups", and in a controller action have a socket subscribe to a group with Group.subscribe(groupId, req.socket). Then you can send messages to a specific group with Group.publish(groupId, data).

You can also subscribe to an arbitrary room name in a controller using req.listen(groupId), and broadcast to that room with req.broadcast(roomName, data).

This is all in the Sails documentation for working with Sockets!

sgress454
  • 24,870
  • 4
  • 74
  • 92
  • 1
    Can you provide more specific example please. Some more code will be useful. Can't seem to find the Group thing in the link provided. – Petar Vasilev Jan 27 '14 at 21:27
  • Group is the name of the model in the example. In the docs they're listed as `Model.subscribe`, `Model.publish`, etc. – sgress454 Jan 27 '14 at 21:46