如何做RPC over socket.io? [英] How to do RPC over socket.io?
问题描述
假设我们有一个简单的echo服务器(在第一个请求中调整为更长的时间):
Suppose we have a simple echo server (tuned to be longer on the first request):
var waiting = 8000;
io.on('connection', function(socket){
socket.on('doEcho', function (data) {
setTimeout( function () {
socket.emit('echoDone', data);
}, waiting);
waiting = 1;
});
});
然后说一个index.html客户端脚本:
Then say a index.html client script does:
askEcho ("11111", function (resp) {
console.log("answer for 11111 " + resp);
});
askEcho ("22222", function (resp) {
console.log("answer for 22222 " + resp);
});
其中 askEcho
假装为RPC存根:
where askEcho
is the following buggy function, pretending to be an RPC stub:
function askEcho (text, fun) {
socket.emit('doEcho', text);
socket.on('echoDone', function (data) {
fun ( data );
});
}
显然我得到的是下面的错误
And obviously what I get is the following mess
answer for 11111 22222
answer for 22222 22222
answer for 11111 11111
answer for 22222 11111
因为我为同一个事件安装了两个监听器。这可以很容易地解决,
,但我没有看到清楚如何获得正确的命令在客户端,
响应在服务器端没有帮助(编程更多)。
because I installed two listeners for the same event. This can be worked around easily, but I don't see that clear how to get the responses properly ordered at the client, without help (programming more) at the server side.
这看起来有点太负担了。
不能是 askEcho
函数编码的权利和轻松?
This all seems a bit too much burden.
Can't be the askEcho
function coded right and easily?
推荐答案
实际上,有一个简单的技巧:使用计数器来区分答案,并在完成后删除回调(更好地使用一次
而不是 on
)。这只会在服务器端和客户端方面做轻微的更改。
让我们看看:
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:
echo服务器是(现在没有任何延迟超时):
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);
});
});
在客户端(index.html)中,用户代码仍然是相同的: / p>
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);
});
,这是stub askEcho
正确地与服务器端的团队合作:
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 );
});
}
这篇关于如何做RPC over socket.io?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!