Search code examples
c++asio

How to create an asio socket with an existing fd and callback into custom code rather than read from it when data is available


I have a C++ application where I'm using a 3rd Party api. As part of that api they will handle the socket connections etc, however, they have a mode where I can select / poll on the fd and then call into the api read from the socket, decode the data and dispatch to the proper handlers; this way we can control the thread where the dispatch code runs. Now I also have extensive use of asio for my networking and I would like to handle this with that. In fact, I desire the api's dispatch code to run on in the asio thread. So, I would like an asio socket that takes the existing fd and then makes a call to what I want when there is data on the fd. This seems pretty straight forward but I can't find it in the docs / examples.


Solution

  • I found what I needed, asio::posix::stream_descriptor. I can assign it the socket handle (fd) and then call async_wait and asio will notify me when there is data to be read:

        descriptor_.assign(connection_.get_socket_handle());
        descriptor_.async_wait(asio::posix::stream_descriptor::wait_read, [this] (const std::error_code& error) { this->handle_data(error); });