我非常渴望将Socket.io集成到我的node.js项目中,但我对如何正确使用socket.io有一些困惑.我一直在查看文档和教程,但我无法理解有关socket.io如何工作的一些概念.
我想到的场景如下:
我在这种情况下的困惑是,当服务器完成数据处理时,它会以下列方式发出响应:
// 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)
})
})
Run Code Online (Sandbox Code Playgroud)
但在这里我没有定义我发送响应的客户端!
我希望我能很好地解释我的疑虑.
socket对象的实例对应于客户端连接.因此,您从该实例发出的每条消息都将发送到打开该套接字连接的客户端.请记住,在connection事件发生时(通过onDone回调)获得套接字连接对象.每次客户端连接到socket.io服务器时,都会触发此事件.
如果要向所有可以使用的客户端发送消息
io.sockets.emit("message-to-all-clients")
如果你想发送一个事件给每个发送事件的客户
socket.broadcast.emit("message-to-all-other-clients");
| 归档时间: |
|
| 查看次数: |
3622 次 |
| 最近记录: |