本文介绍了ZeroMQ:如何将 Poller 中使用的 pollitem_t 项转换回 ZeroMQ 套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,当使用 zmq::pollcppzmq 时,我很想避免将 ZeroMQ 套接字的翻译硬编码为pollitem_t item(s) 用于轮询.

As title says, when using zmq::poll with cppzmq, I'd love to avoid hardcoding the translation of ZeroMQ sockets into pollitem_t item(s) for polling.

但似乎我不允许将 void* pollitem_t::socket 转换回 zmq 套接字.

But it seems that I'm not allowed to convert a void* pollitem_t::socket back to a zmq socket.

我注意到官方示例代码只是在轮询后对套接字进行了硬编码.

I noticed that the official sample code just hardcoded the socket after polling.

//
//  Reading from multiple sockets in C++
//  This version uses zmq_poll()
//
// Olivier Chamoux <[email protected]>

#include "zhelpers.hpp"

int main (int argc, char *argv[])
{
    zmq::context_t context(1);

    //  Connect to task ventilator
    zmq::socket_t receiver(context, ZMQ_PULL);
    receiver.connect("tcp://localhost:5557");

    //  Connect to weather server
    zmq::socket_t subscriber(context, ZMQ_SUB);
    subscriber.connect("tcp://localhost:5556");
    subscriber.setsockopt(ZMQ_SUBSCRIBE, "10001 ", 6);

    //  Initialize poll set
    zmq::pollitem_t items [] = {
        { static_cast<void*>(receiver), 0, ZMQ_POLLIN, 0 },
        { static_cast<void*>(subscriber), 0, ZMQ_POLLIN, 0 }
    };
    //  Process messages from both sockets
    while (1) {
        zmq::message_t message;
        zmq::poll (&items [0], 2, -1);

        if (items [0].revents & ZMQ_POLLIN) {
            receiver.recv(&message);
            //  Process task
        }
        if (items [1].revents & ZMQ_POLLIN) {
            subscriber.recv(&message);
            //  Process weather update
        }
    }
    return 0;
}

因此问题:

在这种情况下是否无法避免硬编码套接字?

Hence the question:

Is it impossible to avoid hardcoding sockets in this case?

推荐答案

从 zmq.hpp 标题中将其拼凑起来:

Puzzled this together from the zmq.hpp header:

zmq::poller_t poller;
poller.add({from_handle, receiver.handle()}, event_flags::pollin});
poller.add({from_handle, subscriber.handle()}, event_flags::pollin});

// This vector must be at least as large as the number of sockets being polled
vector<zmq::poller_event> events(2);
while (true) {
  size_t num_events = poller.wait_all(events, -1);
  // You may need to sleep a bit if num_events == 0

  for (int i = 0; i < num_events; i++) {
    zmq::message message;
    events[i].socket.recv(&message);
    ...
  }
}

意识到poller_event 结构也包含一个socket_ref!这让事情变得更容易了!

Realized that the poller_event structure also contains a socket_ref! That makes things even easier!

对于稳定的 zmq 版本,您需要 #define ZMQ_BUILD_DRAFT_API 以使用 poller_t 及其包.

With a stable zmq release, you need to #define ZMQ_BUILD_DRAFT_API to use poller_t and its bag.

这篇关于ZeroMQ:如何将 Poller 中使用的 pollitem_t 项转换回 ZeroMQ 套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:53