将asio示例http客户端修改为HTTP 1.1

时间:2016-01-02 14:22:25

标签: c++ http boost boost-asio

我正在通过例子学习asio。现在我想更改http client code以支持HTTP 1.1以进行连接重用。

我将请求语句移动到handle_connect函数,修改了请求流,如下所示:

void handle_connect(const asio::error_code& err)
{
  if (!err || err == asio::error::eof)
  {
    std::ostream request_stream(&request_);

    request_stream << "GET " << path << " HTTP/1.1\r\n";
    request_stream << "Host: " << server_ << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: Keep-Alive\r\n\r\n";
    asio::async_write(socket_, request_,
        boost::bind(&client::handle_write_request, this,
          asio::placeholders::error));
  }
  else
  {
    std::cout << "Error: " << err.message() << "\n";
  }
}

然后修改handle_read_content以在完成回复时再次致电handle_connect

void handle_read_content(const asio::error_code& err)
{
  if (!err)
  {
    // Write all of the data that has been read so far.
    std::cout << &response_;

    request_.consume(request_.size());
    response_.consume(response_.size());
    handle_connect(err);
  }
  else if (err != asio::error::eof)
  {
    std::cout << "Error: " << err << "\n";
  }
  else if (err == asio::error::eof)
  {
    request_.consume(request_.size());
    response_.consume(response_.size());
    handle_connect(err);
  }
}

但是代码不起作用,客户端在响应完成后将tcp FIN 置于被动关闭状态。请帮我修复代码。

0 个答案:

没有答案