I just started playing with node.js and the zeromq bindings today and am seeing some behavior that I don’t quite understand.
Here’s my sample code which calls to another ruby based zeromq REP process on port 9000 on the same machine:
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");
I’m hitting the node server using my browser and waiting for a response. What is strange is that the output I get in the console is coming across in an additive manner which I’m not grokking:
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
I tried moving the zmqSocket.on() call outside of the http request block which removes the additive behavior but it also doesn’t then include the request/response objects that I need.
The point of this exercise is to have the browser wait until the response comes back from the long running zeromq server process on port 9000 (currently just a faked up sleep response).
I’m pretty sure I’m just misunderstanding the callback here but can’t find much in the way of documentation on this scenario.
Thanks for any help.
You are rebinding your zmqSocket.on(‘message’, function(data) { event everytime an incoming request comes in. This is causing multiple event binds, move that block of code outside your request handler.