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.
It's obvious that you can't directly call a function on the client from the server.
You can easily do this indirectly, though:
ferret
message, it stores the given function locally with an ID. 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.
The third argument to the emit method accepts a callback that will be passed to the server so that you can call in acknowledgement with any data you wish. It's actually really convenient and saves the effort of having paired call-response events.
Acknowledge is the way to get a response corresponding to a sent message. The following is a code snippet for server-side.
io.sockets.on('connection', function(socket) {
socket.on('echo', function(data, callback) {
callback(data);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.