Socket.io passes callback functions

I wonder what is going on in this scenario

Customer:

socket.emit('ferret', 'tobi', function (data) {
  console.log(data); // data will be 'woot'
});

      

Server:

io.on('connection', function (socket) {
    socket.on('ferret', function (name, fn) {
      fn('woot');
    });   
});

      

This is from the docs. How does it make sense that the function is passed to the server for the callback? How can a server call a client function? I am very confused.

+3


source to share


2 answers


Obviously, you cannot directly call a function on the client from the server.

You can easily do it indirectly, though:

  • When a client sends a message ferret

    , it stores the given function locally with an identifier.
  • The client sends this identifier along with the message to the server.
  • When the server wants to call a client function, it sends a special message with the function identifier and arguments.
  • When the client receives this special message, it can look up the function by its ID and call it.


I don't know if this is exactly what Socket.io does, but it is reasonable to assume that it is something similar to this.


Edit: Looking at the source code ( here and here ) it really looks like what Socket.io does.

+1


source


The third argument to the emit method accepts a callback that will be passed to the server so you can invoke confirmation with whatever data you want. This is actually really convenient and saves the effort associated with paired call answer events.

Acknowledgment is a way to get a response that matches the message sent. Below is the code snippet for the server side.



io.sockets.on('connection', function(socket) {
  socket.on('echo', function(data, callback) {
    callback(data);
  });
});

      

0


source







All Articles