Socket.io:如何处理/管理多个客户端请求和响应?

Cod*_*-JR 6 node.js socket.io

我非常渴望将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)
    })
})
Run Code Online (Sandbox Code Playgroud)

但在这里我没有定义我发送响应的客户端!

  • socket.io如何处理这个?
  • socket.io如何确保:响应Rs1被发送到C1?
  • 是什么确保:响应Rs1没有发送到C2?

我希望我能很好地解释我的疑虑.

jah*_*ado 5

socket对象的实例对应于客户端连接.因此,您从该实例发出的每条消息都将发送到打开该套接字连接的客户端.请记住,在connection事件发生时(通过onDone回调)获得套接字连接对象.每次客户端连接到socket.io服务器时,都会触发此事件.

如果要向所有可以使用的客户端发送消息
io.sockets.emit("message-to-all-clients")

如果你想发送一个事件给每个发送事件的客户 socket.broadcast.emit("message-to-all-other-clients");