ZeroMQ / JZMQ - 订阅者不会收到任何消息

时间:2013-06-27 05:15:28

标签: zeromq jzmq

我检查了ZMQ指南中给出的几个例子,但由于某些原因,subriber没有收到任何信息。这是我试图测试的代码,但是徒劳无功。请为此建议修复 -

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.

请帮我解决这个问题。感谢!!!

2 个答案:

答案 0 :(得分:4)

我假设您正在运行两个程序。一个用于发布者,另一个用于订阅者。

在这种情况下,您需要先启动订阅者,然后启动发布者。

原因是出版商是一个“即发即忘”。它不等待订户连接。这在Getting the Message Out部分的指南中描述为“慢速木匠”症状。

答案 1 :(得分:1)

  1. 您必须先启动发布商。
  2. 然后您可以启动订阅者。

    订阅者何时连接到发布者并不重要。 订阅者连接到发布者并且发布者正在发布数据后,必须获取数据。

    有关示例程序,请参阅以下链接 http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/patterns/pubsub.html

相关问题