2

我很新来提升。我需要一个跨平台的低级 C++ 网络 API,所以我选择了 asio。现在,我已经成功连接并写入了一个套接字,但是由于我使用的是异步读/写,我需要一种方法来跟踪请求(如果你愿意的话,要有某种 ID)。我查看了文档/参考,发现无法将用户数据传递给我的处理程序,我能想到的唯一选择是创建一个特殊的类作为回调并跟踪它的 id,然后传递它到套接字作为回调。有没有更好的办法?或者是最好的方法吗?

4

1 回答 1

3

async_xxx 函数以完成处理程序的类型为模板。处理程序不必是简单的“回调”,它可以是任何公开正确的 operator() 签名的东西。

因此,您应该能够执行以下操作:

// 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));

或者,您也可以将处理程序作为普通函数并将其绑定到调用站点,如asio 教程中所述。上面的示例将是:

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
));
于 2010-01-22T16:42:17.260 回答