Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io : How to handle/manage multiple clients requests and responses?

I am very eager to integrate Socket.io to my node.js project, but I have some confusions on how to properly use socket.io. I have been looking through documentations and tutorials, but I have not been able to understand some concepts on how socket.io works.

The scenario I have in mind is the following:

  • There are multiple clients C1, C2, ..., Cn
  • Clients emit request to the server R1,...,Rn
  • Server receives request, does data processing
  • When data-processing is complete, Server emits response to clients Rs1, .., Rs2

The confusion I have in this scenario is that, when the server has finished data processing it emits the response in the following way:

// 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 have NOT defined which client I am sending the response to!

  • How does socket.io handle this ?
  • How does socket.io make sure that: response Rs1 is sent to C1 ?
  • What is making sure that: response Rs1 is not sent to C2 ?

I hope I have well explained my doubts.

like image 527
Codious-JR Avatar asked Apr 17 '16 10:04

Codious-JR


1 Answers

The instance of the socket object corresponds to a client connection. So every message you emit from that instance is send to the client that opened that socket connection. Remember that upon the connection event you get (through the onDone callback) the socket connection object. This event triggers everytime a client connects to the socket.io server.

If you want to send a message to all clients you can use
io.sockets.emit("message-to-all-clients")

and if you want to send an event to every client apart the one that emits the event socket.broadcast.emit("message-to-all-other-clients");

like image 193
jahnestacado Avatar answered Sep 28 '22 04:09

jahnestacado