Category Archives: JavaScript

ZeroMQ PubSub in NodeJS

Alternate language examples: Python

Yesterday, I posted an entry about how to implement the publish-subscribe model using ZeroMQ in Python.  Today I’ve gone ahead and ported that example over to NodeJS.  You can refer to the original article for a more detailed explanation of what’s going on, I’m simply going to publish the source code below.

Server:

var zeromq = require('zmq');

var socket = zeromq.socket('pub');

socket.bind('tcp://127.0.0.1:2001', function(error) {

    if (error) {
        console.log(error);
    }

    console.log("Listening on port 2001");

    setInterval(function() {

        var face = "Facepalmer";
        var randNumber = Math.floor(Math.random() *
            999999);
        var message = face + " " + randNumber;

        socket.send("ARNOLD " + message);
        // This message should be dropped on the client
        socket.send("FACEPALMER ARNOLD " + message);
        socket.send("ARNOLDFACEPALMER " + message);

    }, 1000);

});

Client:

var zeromq = require('zmq');

var sock = zeromq.socket('sub');
sock.connect('tcp://127.0.0.1:2001');
sock.subscribe('ARNOLD');

sock.on('message', function(data) {
   console.log(data.toString());
});