5

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?
gremo
  • 47,186
  • 75
  • 257
  • 421

3 Answers3

8

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!
gremo
  • 47,186
  • 75
  • 257
  • 421
  • 1
    Actually, the server just sends the arguments you pass to `fn` to the client, so the function is executed there, not on the server. – klh Apr 30 '14 at 00:11
  • yes name is the data sent by the client and they call it name because it refers to 'tobi' name :) – YouneL Jun 01 '17 at 17:25
1

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.

Community
  • 1
  • 1
-1

To send data from client to server

socket.emit("Idofhtmltag",value);

To receive data from server, on client html add this

socket.io("Idofhtmltag",function(msg){  }) ; 
Gajender Singh
  • 1,285
  • 14
  • 13