Asynchronously waiting until a socket is available for reading/writing in Asio
Asked Answered
N

2

9

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.

Nardi answered 28/6, 2013 at 12:2 Comment(2)
Do you want the code that using async_connect, async_write, async_read?Stinnett
Only async_read and async_write. I can do the connect myself as the library uses sockets from already established connections, so I can use async_connect myself.Nardi
G
9

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 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.

Gynaecology answered 28/6, 2013 at 12:38 Comment(1)
null_buffers has been deprecated since Boost 1.66.0: "(Deprecated: Use the socket/descriptor wait() and async_wait() member functions.)"Cordilleras
S
2

Use socket.async_wait(asio::ip::tcp::socket::wait_read, wait_handler);

Southwest answered 2/3, 2021 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.