Question

I hv checked several examples given in the ZMQ guide, but for some reason subsriber does not recieve msgs in any. Here's the code I m trying to test, but in vain. Please suggest a fix for this -

public class SyncPubTest {

    protected static int SUBSCRIBERS_EXPECTED = 2;  

    public static void main (String[] args) {  
        Context context = ZMQ.context(1);  
        Socket publisher = context.socket(ZMQ.PUB);  
        publisher.bind("tcp://*:5561");  
        try {  
            //zmq??  
            Thread.sleep (1000);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }    

        int update_nbr;  
        for (update_nbr = 0; update_nbr < 10; update_nbr++){  
            publisher.send("Rhubarb".getBytes(), ZMQ.NOBLOCK);  
        }  
        publisher.send("END".getBytes(), 0);  

       // publisher.close();  
        //context.term();  
    }  
}  

public class SyncSubTest {

    public static void main(String[] args) {  
        Context context = ZMQ.context(1);  
        Socket subscriber = context.socket(ZMQ.SUB);  
        subscriber.connect("tcp://localhost:5561");  
        subscriber.subscribe("".getBytes());  
        int update_nbr = 0;  
        while (true) {  
            byte[] stringValue = subscriber.recv(0);  
            String string = new String(stringValue);  
            if (string.equals("END")) {  
                break;  
            }  
            update_nbr++;  
            System.out.println("Received " + update_nbr + " updates. :" + string);  
        }  

        //subscriber.close();  
        //context.term();  
    }  
}  

For some reason, context.term()  hangs even all the sockets created in the context are closed.

Please help me fix this issue. Thanks!!!

Was it helpful?

Solution

I assume you're running two programs. One for the publisher and the other for the subscriber.

In this case you need to start the subscriber first and then the publisher.

The reason is that the publisher is a "fire-and-forget". It doesn't wait for subscribers to connect. This is described in the guide in the Getting the Message Out section as the "slow joiner" symptom.

OTHER TIPS

  1. You have to start the publisher first.
  2. Then you can start the subscriber.

    It does not matter when the subscriber is connecting to the publisher. Subscriber must get the data once it connects to the publisher and the publisher is publishing it.

    Refer the following link for sample programs http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/patterns/pubsub.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top