node.js and zeromq, part 3 (Request/Reply)
Today, in part 3 of the series on node.js and zeromq: Request & Reply. This pattern is meant for clients asking multiple requests to (multiple) servers. Contrary to TCP/IP, in zeromq it doesn't matter whether the server or the client does the bind. In the below case, the servers do the connect and the client does the bind. The most stable part of your architecture needs to do the bind.
requestreplyserver.js:
var zeromq = require("zeromq");
// reply = server/service
var socket = zeromq.createSocket('reply');
socket.connect("tcp://127.0.0.1:12345");
socket.on('message', function(data) {
console.log("Received: "+data.toString('utf8'));
socket.send(""+2*data);
});
The server in the above example will multiply every received value with two. In real life situations this doesn't make sense, so use this for expensive operations.
requestreplyclient.js:
var zeromq = require("zeromq");
// request = client
var socket = zeromq.createSocket('request');
socket.bind("tcp://127.0.0.1:12345", function(err) {
if (err) throw err;
console.log("bound!");
setInterval(function() {
var value = Math.floor(Math.random()*100);
socket.send(""+value);
console.log("Asking: "+value);
}, 100);
socket.on('message', function(data) {
console.log("Answer data: "+data);
});
});
