ZMQ and Libevent coexistPosted on November 5, 2012 by Tangfu
You might need to use ZMQ to handle messaging but use Libevent to listen for descriptors. Http://inercia.tumblr.com/post/3442759929/zeromq-with-libevent is a complete example of mixed zmq and libevent.
ZMQ's own encapsulated sockets are actually associated with a descriptor on a Linux system, so you can extract ZMQ sockets from getsockopt
The corresponding system FD is then registered to the libevent. But there are some things to be aware of in use.
1. Online reminders need to first ZMQ the data on the socket, or the event response after registration to Libevent will be problematic, which should be related to ZMQ message subcontracting and edge triggering.
1 2 3 4 5 6
|
while (true) { message_t msg; BOOL more = M_SOCK->RECV (&msg, Zmq_noblock); if (!more) Break } |
2. Some patterns of ZMQ sockets have problems with libevent coexistence
The ZMQ mode limits the socket's direction and strategy, so there are some problems with ZMQ sockets in different modes.
However, the two less restrictive modes of xreq or Xrep are OK.
The 3.ZMQ event trigger is an edge trigger, and the Libevent event trigger is a horizontal trigger. Therefore, each response requires that the data be collected
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
OnEvent () { while (true) { uint32_t events; size_t sz_events = sizeof (events); M_sock->getsockopt (zmq_events, &events, &sz_events); if (! ( Events & Zmq_pollin)) Break int64_t more; size_t more_size = sizeof (more); do { if (!m_sock->recv (&rep, Zmq_noblock)) { LOG (ERROR) << "Zmq_recv ERROR:" << zmq_strerror (errno); Return } M_sock->getsockopt (Zmq_rcvmore, &more, &more_size); } while (more); } } |
4. Even if you have done all 3 of the above, the use of libevent may still appear to lose packets, the following is the scheme given by Brother Bear.
1 2 3 4 5 6 7 8 9
|
while (true) { uint32_t event = 0; size_t Eventsz = sizeof (event); M_sock->getsockopt (zmq_events, &event, &eventsz); if (Event & Zmq_pollin) OnEvent (); Event_base_loop (M_event_base, evloop_once); } |
Original articles, reproduced please specify: Reproduced from the rainy day
This article link address: ZMQ and libevent coexist