简体   繁体   中英

Socket.io passing callback functions

I am perplexed as to what is happening in this scenario

Client:

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 any sense that a function is being passed to the server for the callback? How can the server be calling a client function? I am very confused.

It's obvious that you can't directly call a function on the client from the server.

You can easily do this indirectly, though:

  1. When the client sends the ferret message, it stores the given function locally with an ID.
  2. The client sends this ID along with the message to the server.
  3. When the server wants to call the client function, it sends a special message back with the ID and the arguments to the function.
  4. When the client recieves this special message, it can look up the function by its ID and call it.

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


Edit: Looking at the source code ( here and here ), this does indeed seem to be pretty much what Socket.io does.

The third argument to the emit method accepts a callback that will be passed to the server so that you can call in acknowledgement with any data you wish. It's actually really convenient and saves the effort of having paired call-response events.

Acknowledge is the way to get a response corresponding to a sent message. The following is a code snippet for server-side.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM