2

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

事后[评论]: 经过进一步的测试,我意识到这只是一个愚蠢的副本和过去的错误,并且论据zmq::poll不是我想的那样。第二个参数是列表中的项目数。应该是 2 而不是 1。 – CrimsonKnights 12 月 13 日 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)
     {

     }

 }
4

0 回答 0