views:

242

answers:

1

Hello, I'm pretty new to boost. I needed a cross platform low level C++ network API, so I chose asio. Now, I've successfully connected and written to a socket, but since I'm using the asynchronous read/write, I need a way to keep track of the requests (to have some kind of IDs, if you will). I've looked at the documentation/reference, and I found no way to pass user data to my handler, the only option I can think of is creating a special class that acts as a callback and keeps track of it's id, then pass it to the socket as a callback. Is there a better way? Or is the best way to do it?

+1  A: 

The async_xxx functions are templated on the type of the completion handler. The handler does not have to be a plain "callback", and it can be anything that exposes the right operator() signature.

You should thus be able to do something like this:

// Warning: Not tested
struct MyReadHandler
{
    MyReadHandler(Whatever ContextInformation) : m_Context(ContextInformation){}

    void 
    operator()(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        // Use m_Context
        // ...            
    }

    Whatever m_Context;
};

boost::asio::async_read(socket, buffer, MyReadHander(the_context));

Alternatively, you could also have your handler as a plain function and bind it at the call site, as described in the asio tutorial. The example above would then be:

void 
HandleRead(
    const boost::system::error_code& error, 
    std::size_t bytes_transferred
    Whatever context
)
{
    //...
} 

boost::asio::async_read(socket, buffer, boost::bind(&HandleRead,
   boost::asio::placeholders::error_code,
   boost::asio::placeholders::bytes_transferred,
   the_context
));
Éric Malenfant
Thank you! That worked perfectly.
fingerprint211b