1

这是我在 zeroMQ 中使用 epgm 的发布者和订阅者的代码,其中发布者发布了一个字符串“x”。连续和订阅者应该收到消息,但在这段代码中没有发生。

** 发布者代码:**

include zmq.hpp 
include string 
include unistd.h 
include iostream 
using namespace std;


int main(int argc, char *argv[])
{

    void *context = zmq_init(1);

    void *publisher = zmq_socket(context, ZMQ_PUB);

    zmq_bind(publisher, "epgm://eth0;239.192.1.1:5555");


    string s = "x.";


    while (1)
    {

    zmq_msg_t message;

    zmq_msg_init_size(&message, s.size());

    memcpy(zmq_msg_data(&message), s.c_str(), s.size());


    int rc = zmq_sendmsg(publisher, &message, ZMQ_DONTWAIT);

    }

    sleep(3);

}

订阅者代码:

include zmq.hpp 
include string 
include unistd.h 
include iostream 
using namespace std;

int main(int argc, char *argv[])
{

    zmq::context_t context(1);

    zmq::socket_t subscriber(context, ZMQ_SUB);

    string subscription = "x";

    zmq_connect(subscriber, "epgm://eth0;239.192.1.1:5555");

    const char *filter = (argc > 1) ? argv[1] : "x";

    subscriber.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));

    int ret_val;

    while (1)
    {

    string msg_buffer;

    zmq_msg_t message;

    zmq_msg_init(&message);

    if ((ret_val = zmq_recvmsg(subscriber, &message, ZMQ_DONTWAIT)) < 0)
    {

        cout < "Not receiving";

        cout ret_val;

        sleep(1);

        continue;


    }

    int size = zmq_msg_size(&message);

    msg_buffer.assign((const char *) zmq_msg_data(&message), size);

    cout << "Msg buffer : " << msg_buffer << endl;

    }
    sleep(3);

}

输出:

    Not receiving
    -1

    Not receiving
    -1

    Not receiving
    -1

    Not receiving
    -1

    Not receiving
    -1

    Not receiving
    -1
    Not receiving
    .
    .
    .

请建议我为什么会这样......以及如何解决这个问题?

4

0 回答 0