简体   繁体   中英

zmq python publish c++ subscribe

I have a ZeroMQ publisher in c++ (using zhelpers.hpp ) and ZeroMQ subscriber in python3 (using pyzmq ).

Trouble is, no message is recived in subscriber. I suppose, there is a problem with ZeroMQ filter. I can't figure out, how to properly use .setsockopt() in c++ to recive messages from python publisher.

Python publisher:

    import zmq
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.bind("tcp://*:4004")
    while True:
      command = input("insert command ")
      if (command=='c'):
            topic = "CALL".encode("ascii")
            data = "blabla".encode("ascii")
            socket.send_multipart([topic,data])

C++ subscriber:

    #include "zhelpers.hpp"
    zmq::context_t context(1);
    zmq::socket_t subscriber1 (context, ZMQ_SUB);
    subscriber1.connect("tcp://127.0.0.1:4004");
    subscriber1.setsockopt( ZMQ_SUBSCRIBE, "CALL", 4);
    while (1) {
        // read envelope
        std::string address = s_recv (subscriber1);
        // read message
        std::string contents = s_recv (subscriber1);
        std::cout << "[" << address << "] " << contents << std::endl;

Python subscriber is workking fine. Code:

    subscriber = context.socket(zmq.SUB)
    subscriber.connect("tcp://127.0.0.1:4004")
    subscriber.setsockopt(zmq.SUBSCRIBE, b"CALL")
    [command, contents] = self.subscriber.recv_multipart()

From the docs : setsockopt 's last argument is the length of the option value. In your case the length of the string you are passing as a filter value.

As you put in 8 as the length c++ will read 8 characters but your filter string is only 4 charactes long. That results in a filter which contains some random data. If you are lucky the filter will match sometimes but it's very unlikey.

Change the method call to this:

subscriber1.setsockopt( ZMQ_SUBSCRIBE, "CALL", 4);

You want c++ to only read what is there and not more.

I ended up swiching to C using zhelpers.h. I had to update libzmq-dev to version > 3.2. I used example on zguide: zmq subscriber in c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM