Trying to broadcast socket.io message to all connected sockets in e.g. room

若如初见. 提交于 2019-12-02 10:11:26

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.

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!