I\'m using Boost.Asio for a server application that I\'m writing.
async_send
requires the caller to keep ownership of the data that is being sent until
I solved a similar problem by passing a shared_ptr
to my data to the handler function. Since asio holds on to the handler functor until it's called, and the hander functor keeps the shared_ptr
reference, the data stays allocated as long as there's an open request on it.
edit - here's some code:
Here the connection object holds on to the current data buffer being written, so the shared_ptr
is to the connection object, and the bind
call attaches the method functor to the object reference and the asio call keeps the object alive.
The key is that each handler must start a new asyc operation with another reference or the connection will be closed. Once the connection is done, or an error occurrs, we simply stop generating new read/write requests. One caveat is that you need to make sure you check the error object on all your callbacks.
boost::asio::async_write(
mSocket,
buffers,
mHandlerStrand.wrap(
boost::bind(
&TCPConnection::InternalHandleAsyncWrite,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
void TCPConnection::InternalHandleAsyncWrite(
const boost::system::error_code& e,
std::size_t bytes_transferred)
{