What does Socket.IO send and receive data (confirmations)?

This example from Socket.IO site confuses me. Sending and receiving data (confirmation):

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 actually reproduce this example. I can not understand:

  • Q1 . How it works in the first place. Does the server (when executed fn

    ) automatically transmit the result to the client? Does Socket.IO connect fn

    to the third parameter of the client emit

    ?
  • Q2 : which parameter (not used) name

    is anonymous in the serverfunction (name, fn)

    ? The journal entry shows him undefined

    why?
+3


source to share


3 answers


Found by me, correct me if I am wrong:



  • name

    (what an unlucky name from the official documentation !!!) is actually the data sent by the client .
  • fn

    corresponds to the 3rd parameter of the client code, and when executed (from the server) automatically (?) sends data back to the client. Amazing!
+6


source


Indeed, it becomes much clearer if you rename "fn" to "callback", as shown here: Acknowledgment for the socket.io special event . This 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 acknowledgment. The callback is then executed on the client using the data sent by the server.



0


source


To send data from client to server

socket.emit("Idofhtmltag",value);

      

To fetch data from server, on the html client add this

socket.io("Idofhtmltag",function(msg){  }) ; 

      

0


source







All Articles