0

我今天刚开始使用 node.js 和 zeromq 绑定,并且看到一些我不太理解的行为。

这是我的示例代码,它在同一台机器上的端口 9000 上调用另一个基于 ruby​​ 的 zeromq REP 进程:

var zeromq = require("zmq");
var http = require('http');

var counter = 0;

var availabilityResponse = function(counter, data, request, response) {
    var str = data.toString('utf-8');
    console.log(str);
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write(str);
    response.end();                 
}

var zmqSocket = zeromq.createSocket('request');
zmqSocket.connect("tcp://127.0.0.1:9000");


var server = http.createServer()
server.on('request', function(request, response) {
    counter += 1;
    zmqSocket.send("Hola! - This is call # " + counter);
    zmqSocket.on('message', function(data) {
        availabilityResponse(counter, data, request, response);
    });

});
server.listen(8888);
console.log("Starting HTTP server on port 8888");

我正在使用浏览器访问节点服务器并等待响应。奇怪的是,我在控制台中得到的输出是以一种我不理解的附加方式出现的:

Request received: Hola! - This is call # 1 - Now going to sleep for 1.0

Request received: Hola! - This is call # 2 - Now going to sleep for 3.0
Request received: Hola! - This is call # 2 - Now going to sleep for 3.0

Request received: Hola! - This is call # 3 - Now going to sleep for 3.0
Request received: Hola! - This is call # 3 - Now going to sleep for 3.0
Request received: Hola! - This is call # 3 - Now going to sleep for 3.0

Request received: Hola! - This is call # 4 - Now going to sleep for 2.0
Request received: Hola! - This is call # 4 - Now going to sleep for 2.0
Request received: Hola! - This is call # 4 - Now going to sleep for 2.0
Request received: Hola! - This is call # 4 - Now going to sleep for 2.0

我尝试将 zmqSocket.on() 调用移到 http 请求块之外,这消除了附加行为,但它也不包含我需要的请求/响应对象。

本练习的重点是让浏览器等待响应从端口 9000 上长时间运行的 zeromq 服务器进程返回(当前只是伪造的睡眠响应)。

我很确定我只是误解了这里的回调,但在这种情况下的文档方式中找不到太多。

谢谢你的帮助。

4

2 回答 2

5

每次传入请求时,您都在重新绑定您的 zmqSocket.on('message', function(data) { 事件。这会导致多个事件绑定,将该代码块移到您的请求处理程序之外。

于 2011-08-18T21:03:26.210 回答
0

尝试:

server.on('request', function(request, response) {
    counter += 1;
    zmqSocket.send("Hola! - This is call # " + counter);
    zmqSocket.once('message', function(data) {
        availabilityResponse(counter, data, request, response);
    });

});

这样,该函数每次只会绑定一条消息。

于 2011-08-19T17:40:45.370 回答