Sails.js + socket.io:从服务器向客户端发送消息 [英] Sails.js + socket.io: Sending messages from server to clients
问题描述
我正在尝试使用sails.js 设置一个系统,让服务器向一组客户端广播消息.基本上:
I'm attempting to set up a system with sails.js to have the server broadcast messages to a set of clients. Basically:
- A 组中的客户端向服务器发送 AJAX 请求.
- 服务器处理请求并通过套接字向 B 组的所有客户端发送消息.
- B 组的客户端通过套接字接收消息并显示一些内容.
根据 socket.io 文档,我应该能够让 B 组中的客户端加入房间",然后让服务器广播到该特定房间,但在客户端,预先存在的套接字"没有方法socket.join('room')".所以,我尝试只向所有客户端发送一个独特的事件:
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");
});
通过在服务器端执行 "sails.io.sockets.emit("my_event", {...})" 可以很好地工作,但这不是将事件发送给每个客户端吗?我可以使事件名称唯一,例如my_event_000",带有一个 ID 来指定组,但这仍然会不必要地向每个客户端发送事件.
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?
推荐答案
Sails 实现此目的的方法是让模型支持您的组",并在控制器操作中让套接字订阅带有 Group.subscribe(groupId, req.socket)
.然后,您可以使用 Group.publish(groupId, data)
向特定组发送消息.
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)
.
您还可以使用 req.listen(groupId)
在控制器中订阅任意房间名称,并使用 req.broadcast(roomName, 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)
.
这都在 有关使用套接字的 Sails 文档!
这篇关于Sails.js + socket.io:从服务器向客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!