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.
2 Answers
For sure this depends on what asio framework your are on.
In my libevent-based framework , I implement the operation like this
void BaseConnection::take_socket(evutil_socket_t fd, short event_mask, int options)
{
this->bev = bufferevent_socket_new( get_event_base(), fd, options);
if (!this->bev) {
throw SimpleException("Error constructing bufferevent on fd #%d", fd);
}
bufferevent_setcb(bev, trampoline_readable, trampoline_writable , trampoline_event , (void*) this);
bufferevent_enable(bev, event_mask);
}
After take_socket
gets called, fd
would be taken by a buffered event
(this->bev),
and when income data available, trampoline_readable
will be called.
If you are on boost::asio, though I am not familiar on it, you may have interest on basic_stream_socket::assign
.
Good luck:)
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); });