尝试将socket.io消息广播到所有已连接的套接字,例如房间 [英] Trying to broadcast socket.io message to all connected sockets in e.g. room
问题描述
挑战:
我想使用 SailsJS ,并能够通过socket.io加入房间,并且
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.
我也许可以只发送每个连接的插座一条消息,但非常希望获得一个示例,说明如何使用SailsJS 0.10做到这一点,以及使用SailsJS 0.10方式实现优雅的方法。
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.
我正在查看: https://github.com/balderdashy/sailsChat ,但我认为这与模型本身非常接近,像例如:autosubscribe:['destroy','update']
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.
谢谢!
I。
推荐答案
SailsChat 示例的目的是演示可能会从套接字消息中消除很多麻烦。您可以使用非常少量的后端代码在Sails中创建功能齐全的聊天应用程序,这一点令人印象深刻。对于不适合使用资源充足的pubsub的情况-或者如果您只是不想使用它-Sails会在 sails.sockets
命名空间。文档对其工作方式非常清楚。
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.
要将套接字连接到任意房间,请执行 sails.sockets.join(< socket> ;,< roomName>)
,其中< socket>
是原始套接字(可能来自 req.socket
或套接字ID)。
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).
要将消息广播到房间中的所有套接字,请执行 sails.sockets。广播(< roomName> ;,<数据>)
。
To broadcast a message to all sockets in a room, do sails.sockets.broadcast(<roomName>, <data>)
.
这些和更多方法在 Sails JS文档。
这篇关于尝试将socket.io消息广播到所有已连接的套接字,例如房间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!