【问题标题】:Asynchronous write to socket and user values (boost::asio question)异步写入套接字和用户值(boost::asio 问题)
【发布时间】:2010-01-23 00:50:11
【问题描述】:

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

【问题讨论】:

    标签: c++ boost networking boost-asio


    【解决方案1】:

    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 tutorial 中所述。那么上面的例子就是:

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

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多