gpt4 book ai didi

c++ - 将ZeroMQ与Boost::ASIO一起使用

转载 作者:行者123 更新时间:2023-12-02 10:35:56 27 4
gpt4 key购买 nike

我有一个使用ZeroMQ进行消息传递的C++应用程序。但是它还必须为基于AJAX / Comet的Web服务提供SGCI连接。

为此,我需要一个普通的TCP套接字。我可以通过普通的Posix套接字来做到这一点,但为了保持跨平台的可移植性并使我的生活更轻松(我希望...),我正在考虑使用Boost::ASIO。

但是现在我遇到了ZMQ想要使用它自己的zmq_poll()和ASIO它是io_service.run()的冲突...

有没有办法让ASIO与0MQ zmq_poll()一起使用?

还是有其他推荐的方法来实现这种设置?

注意:我可以通过使用多个线程来解决这一问题-但只有一个小内核/ CPU才能以非常低的SCGI流量运行该程序,因此多线程将浪费资源...

最佳答案

阅读文档herehere之后,特别是本段

ZMQ_FD: Retrieve file descriptor associated with the socket The ZMQ_FD option shall retrieve the file descriptor associated with the specified socket. The returned file descriptor can be used to integrate the socket into an existing event loop; the ØMQ library shall signal any pending events on the socket in an edge-triggered fashion by making the file descriptor become ready for reading.



我认为您可以为每个 null_buffers使用 zmq_pollitem_t 并将事件循环推迟到 io_service,完全完全绕开 zmq_poll()。但是,上述文档中似乎有一些警告,特别是

The ability to read from the returned file descriptor does not necessarily indicate that messages are available to be read from, or can be written to, the underlying socket; applications must retrieve the actual event state with a subsequent retrieval of the ZMQ_EVENTS option.



因此,当您的一个zmq套接字的处理程序被触发时,在处理我认为的事件之前,您需要做更多的工作。未编译的伪代码如下
const int fd = getZmqDescriptorSomehow();
boost::asio::posix::stream_descriptor socket( _io_service, fd );
socket->async_read_some(
boost::asio::null_buffers(),
[=](const boost::system::error_code& error)
{
if (!error) {
// handle data ready to be read
}
}
);

请注意,您不必在这里使用lambda,将 boost::bind用作成员函数就足够了。

关于c++ - 将ZeroMQ与Boost::ASIO一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60314130/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com