How to do RPC over socket.io?

偶尔善良 提交于 2019-12-01 06:24:51
cibercitizen1

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 );
     });
 }

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!