I solved a similar problem by passing shared_ptr my handler function data. Since asio holds onto the handler functor until it is called, and the guard functor saves the shared_ptr link, the data remains highlighted as long as it has an open request.
edit - here is the code:
Here, the connection object rests on the current data buffer that is being written, so shared_ptr refers 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 a different link or the connection will be closed. As soon as the connection is completed or an error occurs, we simply stop generating new read / write requests. One caveat is that you need to make sure that you check the error object in all of 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) {
Tim sylvester
source share