Suppose we have a simple echo server (tuned to be longer on the first request):
var waiting = 8000;
io.on(\'
With socket.io you can send and receive acknowledgements via callbacks.
See this: http://socket.io/docs/#sending-and-getting-data-(acknowledgements)
Actually, there is a simple trick: use a counter to differentiate between the answers, and remove the callback when done (even better use once
instead of on
). This only poses minor changes at server and client sides.
Let's show it:
The echo server is (now without any delaying timeout):
io.on('connection', function(socket){
socket.on('doEcho', function (callCounter, data) {
socket.emit('echoDone'+callCounter, data);
});
});
In the client side (index.html
) the user code is still the same, as desired:
askEcho ("11111", function (resp) {
console.log("answer for 11111 " + resp);
});
askEcho ("22222", function (resp) {
console.log("answer for 22222 " + resp);
});
and this is the stub askEcho
that works properly in teamwork with the server side:
var callCounter = 0;
function askEcho (text, fun) {
var localCallCounter = ++callCounter;
socket.emit('doEcho', localCallCounter, text);
socket.once('echoDone'+localCallCounter, function (data) {
// not required: socket.removeListener ('echoDone'+localCallCounter);
fun ( data );
});
}