Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 600
jozenbasin Avatar asked Apr 14 '26 20:04

jozenbasin


1 Answers

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.

like image 187
Frxstrem Avatar answered Apr 16 '26 09:04

Frxstrem