使用 Boost.Beast 异步读取 header

Asynchronous read header with Boost.Beast

我尝试单独阅读 header,但在使用任何主机时出现错误。

Class 成员:

boost::asio::io_context ioc_;
// The SSL context is required, and holds certificates
boost::asio::ssl::context ctx_{boost::asio::ssl::context::sslv23_client};
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> stream_{ioc_, ctx_}; // https
boost::asio::ip::tcp::socket socket_{ioc_}; // http
boost::beast::http::request_parser<boost::beast::http::string_body> header_parser_;
boost::asio::streambuf strbuf_;

方法:

void AsyncHttpClient::onWrite(boost::system::error_code ec, std::size_t bytes_transferred)
{
  boost::ignore_unused(bytes_transferred);

  if(ec)
    return fail(ec, "write");

  if (https_mode_) {
    boost::beast::http::async_read_header(socket_, strbuf_, header_parser_, std::bind(&AsyncHttpClient::onReadHeader, this, std::placeholders::_1, std::placeholders::_2));
  }
  else {
    // Receive the HTTP response
    boost::beast::http::async_read_header(socket_, strbuf_, header_parser_, std::bind(&AsyncHttpClient::onReadHeader, this, std::placeholders::_1, std::placeholders::_2));
  }
}

void AsyncHttpClient::onReadHeader(boost::system::error_code ec, std::size_t bytes_transferred)
{
  boost::ignore_unused(bytes_transferred);

  std::cout << bytes_transferred << std::endl;

  if(ec)
    return fail(ec, "read header"); // Here is the error `bad method`

  std::string header_{boost::asio::buffers_begin(strbuf_.data()), boost::asio::buffers_begin(strbuf_.data()) + static_cast<signed long>(bytes_transferred)};
  std::cout << header_ << std::endl;

  std::string s =
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: 5\r\n"
      "\r\n"
      "*****";
  boost::beast::error_code ec_;
  boost::beast::http::request_parser<boost::beast::http::string_body> p;
  p.put(boost::asio::buffer(s), ec_);
  if (ec_) {
    return fail(ec_, "parse header"); // Here is the error `bad method`
  }
}

fail的代码:

void AsyncHttpClient::fail(boost::system::error_code ec, const char *what)
{
  std::cerr << what << ": " << ec.message() << "\n";
}

Header 响应:

HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.6.6
Date: Wed, 03 Oct 2018 13:02:12 GMT
Content-type: text/x-c++src
Content-Length: 205
Last-Modified: Mon, 17 Sep 2018 14:04:14 GMT

另外,Boost.Beast的开发者提出的也不行——同样的错误。

Boost 版本 1.68

我是不是做错了什么?

编辑:

示例中有错字。应该是:

std::string s =
    "POST /cgi/message.php HTTP/1.1\r\n"
    "Content-Length: 5\r\n"
    "\r\n"
    "abcde";

但是异步读取的主要问题header没有解决

我解决了这个问题。

必须使用另一个解析器

boost::beast::http::response_parser<boost::beast::http::file_body> header_parser_;

改为

boost::beast::http::request_parser<boost::beast::http::string_body> header_parser_;

之前我尝试了所有方法,但由于某种原因并没有带来成功。