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:
fn
) automagically emits the result to the client? Does Socket.IO bind fn
to the client third parameter of emit
?name
parameter in server anonymous function (name, fn)
? Logging it shows that it's undefined
, why?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!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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With