gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:40:13 25 4
gpt4 key购买 nike

我正在尝试将 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com