ZMQ Xpub / Xsub不发送订阅消息

时间:2019-12-13 00:14:59

标签: c++11 zeromq xpub

我正在使用 XPUB/XSUB 代理对ZMQ进行试验。最终,我想在中间插入一些逻辑,因此我尝试使用zmq_poll()构建自己的代理,而不是使用内置的zmq_proxy。但是我的XPUB从未收到任何要转发的订阅消息。如果我使用内置代理,则下面的代码有效(订户打印"helloWorld")。它不适用于我的自定义代理。我尝试设置非常冗长/手动的套接字选项并添加延迟,但似乎无法使其工作:

  

事后[评论]:   经过进一步测试后,我意识到这只是一个傻瓜副本和过去的错误,zmq::poll的参数不是我所想的。第二个参数是列表中的项目数。应该是2而不是1。– CrimsonKnights Dec 13 at 5:45   

void proxyBuiltIn(zmq::context_t* context)
{
    zmq::socket_t frontend(*context, ZMQ_XSUB);
    zmq::socket_t  backend(*context, ZMQ_XPUB);
    frontend.bind("inproc://frontend");
    backend.bind("inproc://backend");
    zmq::proxy(frontend, backend);
 }

 void proxyCustom(zmq::context_t* context)
 {
     zmq::socket_t frontend(*context, ZMQ_XSUB);
     zmq::socket_t  backend(*context, ZMQ_XPUB);
     frontend.bind("inproc://frontend");
     backend.bind("inproc://backend");

     zmq::pollitem_t items[2] =
     {
         { frontend, 0, ZMQ_POLLIN, 0 },
         {  backend, 0, ZMQ_POLLIN, 0 },
     };

     while (1)
     {
         if (zmq::poll(items, 1, 1000) == -1){ break;}
         if (items[0].revents & ZMQ_POLLIN)
         {
             std::cout << "got published message" << std::endl; // won't get here because subscription is not made
             zmq::multipart_t message;
             message.recv(frontend);
             message.send(backend);
         }

         if (items[1].revents & ZMQ_POLLIN)
         {
             std::cout << "got subscription message" << std::endl; // never gets here.
             zmq::multipart_t message;
             message.recv(backend);
             message.send(frontend);
         }
     }
 }

 void subscriber(zmq::context_t* context)
 {
     zmq::socket_t subscriber(*context, ZMQ_SUB);
     subscriber.connect("inproc://backend");
     std::string topic = "testTopic";
     subscriber.setsockopt(ZMQ_SUBSCRIBE, topic.c_str(), topic.size());

     while (1)
     {
         zmq::multipart_t incoming;
         incoming.recv(subscriber);

         std::string topic = incoming.popstr();
         std::string data = incoming.popstr();
         std::cout << topic.c_str() << ", " << data.c_str() << std::endl;
     }
 }

 void publisher(zmq::context_t* context)
 {
     zmq::socket_t publisher(*context, ZMQ_PUB);
     publisher.connect("inproc://frontend");

     while (1)
     {
         zmq::multipart_t message;
         message.addstr("testTopic");
         message.addstr("helloWorld!");
         message.send(publisher);
         std::this_thread::sleep_for(std::chrono::milliseconds(1000));
     }
 }

 int main(int argc, char **argv)
 {
     zmq::context_t* context = new zmq::context_t(1);
     std::thread(proxyCustom,  context).detach(); // this does not
  // std::thread(proxyBuiltIn, context).detach(); // this works
     std::thread( publisher, context).detach();
     std::thread(subscriber, context).detach();
     while(1)
     {

     }

 }

0 个答案:

没有答案