异步等待,直到套接字可用于在Asio中读写 [英] Asynchronously waiting until a socket is available for reading/writing in Asio

查看:134
本文介绍了异步等待,直到套接字可用于在Asio中读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对Boost Asio进行以下操作.我有一个套接字,我想注册一个可在套接字上读取/写入数据的回调,但是我不希望它实际执行读取/写入.基本上,除了没有完成实际的读写操作外,我需要的与async_read_some/async_write_some类似.

I want to do the following with Boost Asio. I have a socket and I want to register a callback to be called when data is available for reading/writing on the socket, but I don't want it to actually do the reading/writing. Basically, what I need is similar to async_read_some/async_write_some, except that the actual reading and writing is not done.

之所以需要它,是因为我正在使用具有自己的读写功能的外部库,该函数需要将套接字描述符作为输入参数,并且希望以异步方式使用此库.

I need this because I'm using an external library with its own read and write function that require a socket descriptor as an input parameter and I want to use this library in an asynchronous way.

推荐答案

您正在寻找反应堆式的操作.这些可以通过提供 boost::asio::null_buffers 进行异步操作.反应堆样式的操作对于与第三方库集成,使用共享内存池等的集成很有用.Boost.Asio

You are looking for reactor-style operations. These can be obtained by providing boost::asio::null_buffers to the asynchronous operations. Reactor-style operations can be useful for integrating with third party libraries, using shared memory pools, etc. The Boost.Asio documentation provides some information and the following example code:

ip::tcp::socket socket(my_io_service);
...
socket.non_blocking(true);
...
socket.async_read_some(null_buffers(), read_handler);
...
void read_handler(boost::system::error_code ec)
{
  if (!ec)
  {
    std::vector<char> buf(socket.available());
    socket.read_some(buffer(buf));
  }
}

Boost.Asio还提供了官方

Boost.Asio also provides an official nonblocking example, illustrating how to integrate with libraries that want to perform the read and write operations directly on a socket.

这篇关于异步等待,直到套接字可用于在Asio中读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆