我非常渴望将 Socket.io 集成到我的 node.js 项目中,但我对如何正确使用 socket.io 有一些困惑。我一直在浏览文档和教程,但我无法理解有关 socket.io 工作原理的一些概念。
我想到的场景如下:
- 有多个客户端C1,C2,...,Cn
- 客户端向服务器发出请求 R1,...,Rn
- 服务器接收请求,进行数据处理
- 当数据处理完成后,服务器向客户端发出响应 Rs1, .., Rs2
我在这种情况下感到困惑的是,当服务器完成数据处理后,它会以下列方式发出响应:
// server listens for request from client
socket.on('request_from_client', function(data){
// user data and request_type is stored in the data variable
var user = data.user.id
var action = data.action
// server does data processing
do_some_action(..., function(rData){
// when the processing is completed, the response data is emitted as a response_event
// The problem is here, how to make sure that the response data goes to the right client
socket.emit('response_to_client', rData)
})
})
但是这里我没有定义我要将响应发送给哪个客户端!
- socket.io 如何处理这个问题?
- socket.io 如何确保:将响应 Rs1 发送到 C1?
- 是什么确保:响应 Rs1 没有发送到 C2?
我希望我已经很好地解释了我的疑惑。
最佳答案
socket
对象的实例对应于客户端连接。因此,您从该实例发出的每条消息都会发送到打开该套接字连接的客户端。请记住,在发生 connection
事件时,您会(通过 onDone 回调)获得套接字连接对象。每次客户端连接到 socket.io 服务器时都会触发此事件。
如果你想向所有客户端发送消息,你可以使用
io.sockets.emit("message-to-all-clients")
如果你想发送一个事件给除了发出事件的客户端之外的每个客户端
socket.broadcast.emit("message-to-all-other-clients");
关于node.js - 套接字 : How to handle/manage multiple clients requests and responses?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675090/