Socket.io: How to handle or manage multiple client requests and responses?

I really want to integrate Socket.io into my node.js project, but I have some confusion about how to use socket.io correctly. I was looking through documentation and tutorials, but I was not able to understand some concepts about how socket.io works.

The scenario that I have in mind is the following:

  • There are several clients C1, C2, ..., Cn
  • Clients issue a request to server R1, ..., Rn
  • The server receives a request whether data processing
  • When data processing is completed, the server issues a response to clients Rs1, .., Rs2

The confusion that I have in this scenario is that when the server has finished processing the data, it gives the answer as follows:

// 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)
    })
})

But here I did NOT determine to which client I am sending the answer!

  • .io?
  • .io , : Rs1 C1?
  • : Rs1 C2?

, .

+4
1

socket . , , , . , connection ( onDone) . , socket.io.

, io.sockets.emit("message-to-all-clients")

, socket.broadcast.emit("message-to-all-other-clients");

+3

All Articles