c++ - 为什么Boost-Beast 给我部分消息异常

标签 c++ http boost boost-asio boost-beast

我正在尝试将 boost beast http 库用于 HTTP 客户端。当我使用模拟服务器时,它可以正常工作,但是当我尝试连接到真实服务器时,boost::beast::http::read抛出一个异常,说“部分消息”。
我已经在这个问题上工作了几天,但我不知道为什么。到目前为止,我一直在使用不同的 http 客户端库,并且服务器通信一直在工作,没有任何类似的问题。
对于为什么会发生这种情况以及为什么在使用不同的库时它似乎不是问题的任何想法或提示,我将不胜感激。

最佳答案

boost::beast::http::read throws an exception saying "partial message".


发生这种情况是因为正在解析的消息不完整。一个典型的原因是内容长度 header 错误,或者发送方过早放弃连接。例如。:
Live On Compiler Explorer
这是什么http::[async_]read最终在幕后做,但没有网络相关的东西:
#include <iostream>
#include <iomanip>
#include <string_view>
#include <boost/beast/http.hpp>

int main() {
    using namespace boost::beast::http;
    using boost::asio::buffer;

    for (std::string_view buf : {
            "GET / HTTP/1.1\r\n", // incomplete headers
            "GET / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 0\r\n\r\ntrailing data",
            "GET / HTTP/1.1\r\nHost: example.com\r\nContent-Length: 42\r\n\r\nshort",
        })
    {
        //std::cout << std::quoted(test) << "\n";
        std::cout << "---------------------" << "\n";

        request_parser<string_body> parser;
        boost::system::error_code ec;

        size_t n = parser.put(buffer(buf), ec);
        if (n && !ec && !parser.is_done()) {
            buf.remove_prefix(n);
            n = parser.put(buffer(buf), ec); // body
        }
        if (!ec)
            parser.put_eof(ec);
        buf.remove_prefix(n);

        std::cout
            << (parser.is_header_done()?"headers ok":"incomplete headers")
            << " / " << (parser.is_done()?"done":"not done")
            << " / " << ec.message() << "\n";
        if (parser.is_header_done() && !parser.is_done())
            std::cout << parser.content_length_remaining().value_or(0) << " more content bytes expected\n";

        if (!buf.empty())
            std::cout << "Remaining buffer: " << std::quoted(buf) << "\n";
    }
}
打印
---------------------
incomplete headers / not done / need more
---------------------
headers ok / done / Success
Remaining buffer: "trailing data"
---------------------
headers ok / not done / partial message
37 more content bytes expected
如果你没有通过 error_code对于您的调用,他们会抛出异常 system_error使用相同的代码,这正是您所看到的。
边注
如果另一个图书馆没有这个“问题”,有两个选择:
  • 图书馆马虎(即糟糕)
  • 你用错了(也许你没有检查错误)
  • 关于c++ - 为什么Boost-Beast 给我部分消息异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66140059/

    相关文章:

    c++ - 如何通过 POP3 在 C++ 中接收电子邮件?

    c++ - 查找参数化数组的大小

    javascript 代码在浏览器中不起作用?

    http - 给定无效 ID 时应返回什么 HTTP 状态代码?

    c++ - Boost::signals2 - 传递信号槽作为参数

    c++ - 哪种数据类型可以容纳 10^31 十进制数?

    c++ - 如何正确使用IoC容器?

    java - 访问 Shoutcast 当前流信息

    c++ - 无法安装 R 包 "BH"

    c++ - 预编译 boost 库包 (Ubuntu)