Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's Socket.IO sending and getting data (acknowledgements)?

This example from Socket.IO website is confusing me. Sending and getting data (acknowledgements):

Client:

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

Server:

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

I'm actually reproducing this example. What I can't understand is:

  • Q1: How does this work in the first place. Does the server (when executing fn) automagically emits the result to the client? Does Socket.IO bind fn to the client third parameter of emit?
  • Q2: What's the (unused) name parameter in server anonymous function (name, fn)? Logging it shows that it's undefined, why?
like image 267
gremo Avatar asked Feb 19 '13 07:02

gremo


2 Answers

Found by myself, correct me if I'm wrong:

  • name (what unlucky name from the official documentation!!!) is actually the data sent by the client.
  • fn corresponds to the 3th parameter of client code, and when executed (from the server) automagically (?) sends the data back to the client. Amazing!
like image 106
gremo Avatar answered Oct 04 '22 19:10

gremo


Indeed; it gets a lot clearer if you rename "fn" to "callback", as seen here: Acknowledgment for socket.io custom event. That callback is never executed on the server side; the server simply sends the data passed to the callback (in this case, the string "woot") back to the client as an acknowledgement. The callback is then executed on the client using the data sent by the server.

like image 41
Chris Sladky Avatar answered Oct 04 '22 20:10

Chris Sladky