node.js and zeromq, part 2 (Publish/Subscribe)
While I'm at it, evaluating zeromq that is, I might as well publish examples for all usage patterns, so today follows Publish/Subscribe. The pattern is used to distribute data from one publisher to many subscribers. Both sockets are again uni-directional.
publishsubscribeserver.js:
var zeromq = require("zeromq");
// publisher = send only
var socket = zeromq.createSocket('publisher');
var stocks = ["AAPL", "GOOG", "YHOO", "MSFT", "INTC"];
socket.bind("tcp://127.0.0.1:12345", function(err) {
if (err) throw err;
console.log("bound!");
setInterval(function() {
var symbol = stocks[Math.floor(Math.random()*stocks.length)];
var value = Math.random()*1000;
socket.send(symbol+" "+value);
console.log("Sent: "+symbol+" "+value);
}, 100);
});
The server sends out messages, for five different stock symbols and their value (all random).
publishsubscribeclient.js:
var zeromq = require("zeromq");
// subscriber = receive only
var socket = zeromq.createSocket('subscriber');
socket.connect("tcp://127.0.0.1:12345");
socket.subscribe("AAPL");
socket.subscribe("GOOG");
console.log("connected!");
socket.on('message', function(data) {
console.log("received data: " + data.toString('utf8'));
});
The client subscribes only to receive updates for GOOG (Google) and AAPL (Apple) stock. Please note that the data consists of both the stock symbol and the stock value, exactly what was sent.
zeromq.node is available from GitHub
