Search code examples
c++zeromqrecv

zeroMQ: zmq_recv() doesn't work


I am using zeroMQ to realize the send-recv message. I use this pattern: PUB-SUB.
However, it seems that I can send some message from the publisher but I couldn't receive it from the subscriber. Here is my code:

//subscriber:

int main(int argc, char** argv){
    void * context = zmq_ctx_new();
    void * subscriber = zmq_socket(context, ZMQ_SUB);
    zmq_connect(subscriber, "tcp:://127.0.0.1:5556");
    const int SIZE = 20;
    char msg[SIZE];
    cout<<"receiving..."<<endl;
    cout<<zmq_recv(subscriber, msg, SIZE, 0)<<endl;
    cout<<"received";
    zmq_close(subscriber);
    zmq_ctx_destroy(context);
    return 0;
}

//publisher:

int main(int argc, char** argv){
    void * context = zmq_ctx_new();
    void * publisher = zmq_socket(context, ZMQ_PUB);
    zmq_bind(publisher, "tcp://127.0.0.1:5556");
    srandom((unsigned)time(NULL));
    char updateMsg[20] = "hello world";
    while(1)
    {
        cin.get();
        cout<<"sending..."<<endl;
        cout<<zmq_send(publisher, updateMsg, 20, 0)<<endl;
        cout<<"sent"<<endl;
    }
    zmq_close(publisher);
    zmq_ctx_destroy(context);
    return 0;
}

Now, I run the publisher then I run the subscriber.
Then I type "Enter" at the publisher and it says:

sending...
20
sent<l

BUT, at the subscriber, it always shows only this line: receiving...
It seems that zmq_recv() is blocked.

Could you please help me?


Solution

  • For the PUB-SUB pattern, we MUST use setsockopt to set a filter for the subscriber. Otherwise, the subscriber can't receive ANY message. So for this case, what we should do is to add the code below for the subscriber before the zmq_recv: zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "hello", strlen("hello"));