Trying to broadcast socket.io message to all conne

2020-05-03 13:14发布

问题:

Challenge:

I would like to use SailsJS, and be able to join a room, by means of socket.io, and receive unsolicited messages from this room, not just when one enters or leaves the room but also receive objects.

So several clients connect to the server. Afterwards broadcast (initiated from the server) messages/objects to every room and thus everey connected socket in this room.

I maybe could just send every connected socket a message, but dearly would like a example on how to do this with SailsJS 0.10, and a elegant method in the SailsJS 0.10 way.

I am looking at : https://github.com/balderdashy/sailsChat, but I think this is to close to the models themselves, with like e.g: autosubscribe: ['destroy', 'update']

In my opinion this should be more loosely coupled, and not so tied to the model itself.

Thanks in advance!

I.

回答1:

The purpose of the SailsChat example is to demonstrate how Sails JS resourceful pubsub can take a lot of hassle out of socket messaging when you are mainly concerned with sending messages about models. The fact that you can make a full-featured chat app in Sails with very little back-end code is what makes it impressive. For situations where resourceful pubsub is not appropriate--or if you just plain don't want to use it--Sails exposes lower-level methods on the sails.sockets namespace. The docs are pretty clear on how they work.

To join a socket to an arbitrary room, do sails.sockets.join(<socket>, <roomName>), where <socket> is either a raw socket (probably from req.socket or a socket ID).

To broadcast a message to all sockets in a room, do sails.sockets.broadcast(<roomName>, <data>).

These and more methods are described in detail in the Sails JS documentation.



回答2:

I'm just starting with SailsJS, and already a big fan. I need to find out if this is also scalable with e.g. Heroku or other flavors of SAAS providers, but seems not that hard.

So just a follow up on what I did with SailsJS 0.10:

Server-side:

Made a controller with the following:

join: function (req, res) {

  if (req.isSocket === true) {

    sails.sockets.join(req.socket, 'mysecretroom');
    return res.send(200, 'joined');

  }

  return res.send(200);

},
sendToRoom: function( req, res ) {
  if (req.isSocket === true ) {
     sails.sockets.broadcast('mysecretroom', 'messageevent', {message:'Listen very carefully, I'll shall say this only once..!'});
  }
  return res.send(200);
}

Client-side:

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

+1 kudos @sgress454!

Thanks!