How to do RPC over socket.io?

前端 未结 2 505
悲&欢浪女
悲&欢浪女 2021-01-13 04:39

Suppose we have a simple echo server (tuned to be longer on the first request):

var waiting = 8000;
io.on(\'         


        
相关标签:
2条回答
  • 2021-01-13 05:26

    With socket.io you can send and receive acknowledgements via callbacks.

    See this: http://socket.io/docs/#sending-and-getting-data-(acknowledgements)

    0 讨论(0)
  • 2021-01-13 05:32

    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 );
         });
     }
    
    0 讨论(0)
提交回复
热议问题