Search code examples
javanode.jssocketszeromqdata-stream

Node.JS and Java PUB/SUB


I'm trying to build an application that the communication will be done by a node.js server. This node server will receive messages from others peers.

My node.js code is:

var zmq = require('zmq'),
    socket = zmq.socket('sub');

socket.bind('tcp://127.0.0.1:5556', function (err) {
    if (err) {
        console.log('Error: ', err);
        throw err;
    }

    socket.on('message', function (envelope, blank, data) {
        console.log(arguments);
    });

    socket.on('error', function (err) {
        console.log(arguments);
    });
});

In the other part of the system, there is a java server that should send messages for this server. This is my java code:

Context context = ZMQ.context(1);
Socket publisher = context.socket(ZMQ.PUB);
publisher.connect("tcp://127.0.0.1:5556");
for (int request_nbr = 0; request_nbr < 10; request_nbr++) {
    publisher.send("Hello");
}

For now, my java server is running locally and my node.js is running inside a docker with the port 5556 exposed.
I have success sending messages from the java server. But no message is received in my node.js server.

There is any problem in my ZeroMQ initialization?


Solution

  • Yes, there is a problem:

    As defined in the ZeroMQ protocol-specifications, the SUB-Formal Scalable Communication Pattern archetype has an empty subscription list upon it's instantiation.

    Empty SUB-side subscription is the cause:

    Your SUB-side has to indeed subscribe to anything else ( be it at least a "" - yes - an empty string is enough, for starting receiving any and all messages, or may setup some problem/context-specific string(s), as TOPIC-filter, where each message will start to get tested for a presence of at least one of such TOPIC-s, and discarded ( not .recv()-ed or not promoted into the hands of .on( 'message', ... ) handler at all ).

    Anyway, enjoy the ZeroMQ powers for the distributed computing!