使用cpp-netlib的异步客户端响应

Async client response with cpp-netlib?

本文关键字:客户端 响应 异步 cpp-netlib 使用      更新时间:2023-10-16

我正在考虑为一个新项目使用cpp-netlib。所有的例子都显示了以阻塞的方式读取响应的主体:

client::response response_ = client_.get(request_);
std::string body_ = body(response_);

如果我用async标签构造我的客户端对象:

basic_client<http_async_8bit_udp_resolve_tags, 1, 1> client_();

这有什么影响?

是否可以将body包装器的结果作为boost::shared_future<std::string>

我只需要将阻塞调用封装在它自己的线程中吗?

查看当前http客户端文档:http://cpp-netlib.org/0.12.0/reference/http_client.html

  1. http客户端现在默认情况下总是异步的
  2. 您可以选择在getpost调用中提供回调函数或对象:

    struct body_handler {
        explicit body_handler(std::string & body)
        : body(body) {}
        BOOST_NETWORK_HTTP_BODY_CALLBACK(operator(), range, error) {
            // in here, range is the Boost.Range iterator_range, and error is
            // the Boost.System error code.
            if (!error)
                body.append(boost::begin(range), boost::end(range));
        }
        std::string & body;
    };
    // somewhere else
    std::string some_string;
    response_ = client_.get(request("http://cpp-netlib.github.com/"),
                        body_handler(some_string));
    
  3. client::response对象已经封装了future对象:

响应对象封装了一旦值可用就会填充的期货。