[英]How to fix Boost::Asio Client Http request error?
I'm trying to lean Boost ::Asio networking library for C++ by watching this video but I stuck at making request using threads asynchronously.我正在尝试通过观看此视频来精简 C++ 的Boost ::Asio 网络库,但我坚持使用异步线程发出请求。
The code:编码:
#include "stdafx.h"
#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/ts/buffer.hpp>
#include <boost/asio/ts/internet.hpp>
#include <boost/system/error_code.hpp>
std::vector<char> vBuffrer(20 * 1024);
void GrabSomeData(boost::asio::ip::tcp::socket& socket) {
socket.async_read_some(boost::asio::buffer(vBuffrer.data(), vBuffrer.size()),
[&](std::error_code ec, std::size_t length)
//boost::system::error_code ec
{
if (!ec)
{
std::cout << "\n\nRead" << length << "bytes\n\n";
for (int i = 0; i < length; i++)
std::cout << vBuffrer[i];
GrabSomeData(socket);
}
});
}
int main()
{
boost::system::error_code ec;
boost::asio::io_context context;
boost::asio::io_context::work idleWork(context);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::make_address("13.107.21.200",ec),80);
boost::asio::ip::tcp::socket socket(context);
std::thread thrContext = std::thread([&]() {context.run(); });
std::cout << "Starting " << std::endl;
socket.connect(endpoint,ec);
if (!ec)
{
std::cout << "Connected ! " << std::endl;
}
else {
std::cout << "Fail to connect ! " << ec.message() << std::endl;
}
if (socket.is_open()) {
GrabSomeData(socket);
std::string sRequest =
"GET /index.html HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: close\r\n\r\n";
socket.write_some(boost::asio::buffer(sRequest.data(), sRequest.size()), ec);
using namespace std::chrono_literals;
std::this_thread::sleep_for(2800ms);
//std::this_thread::sleep_for(1ms);
context.stop();
if (thrContext.joinable()) thrContext.join();
}
system("pause");
return 0;
}
Microsoft Visual studio give me this: Microsoft Visual Studio 给我这个:
Error C2752 'asio_prefer_fn::call_traits<boost::asio::execution::any_executor<boost::asio::execution::context_as_t<boost::asio::execution_context &>,boost::asio::execution::detail::blocking::never_t<0>,boost::asio::execution::prefer_only<boost::asio::execution::detail::blocking::possibly_t<0>>,boost::asio::execution::prefer_only<boost::asio::execution::detail::outstanding_work::tracked_t<0>>,boost::asio::execution::prefer_only<boost::asio::execution::detail::outstanding_work::untracked_t<0>>,boost::asio::execution::prefer_only<boost::asio::execution::detail::relationship::fork_t<0>>,boost::asio::execution::prefer_only<boost::asio::execution::detail::relationship::continuation_t<0>>> &,void (const boost::asio::execution::detail::blocking::possibly_t<0> &,boost::asio::execution::allocator_t<std::allocator<void>>),void>': more than one partial specialization matches the template argument list boostasiotest c:\boost\boost_1_75_0\boost\asio\detail\handler_work.hpp 353
Error C2893 Failed to specialize function template 'enable_if<asio_prefer_fn::call_traits<T,void(P0,P1,PN...),void>::overload==,call_traits<T,void(P0,P1,PN...),void>::result_type>::type asio_prefer_fn::impl::operator ()(T &&,P0 &&,P1 &&,PN &&...) noexcept(<expr>) const' boostasiotest c:\boost\boost_1_75_0\boost\asio\detail\handler_work.hpp 353
Everything worked fine till I added GrabSomeData function and I have absolutely no idea how to fix it, any help would be appreciated.在我添加GrabSomeData function 之前一切正常,我完全不知道如何修复它,任何帮助将不胜感激。
PS: there is an example on the Boost website on this subject , but it is object oriented and all the pointers are referring to the class and I (think) it can't help. PS: Boost网站上有一个关于这个主题的例子,但它是面向object的,所有的指针都指向class,我(认为)它无济于事。
Like the commenter, I cannot repro your message: it just compiles,像评论者一样,我无法复制您的信息:它只是编译,
Now, I do see other issues:现在,我确实看到了其他问题:
write_some
may not write all the data - you will want to ensure a composed-write operation write_some
可能不会写入所有数据 - 您需要确保组合写入操作
a race condition: since you're doing GrabSomeData
on a thread, you need to synchronize access to the tcp::socket
and buffer
(the shared resources).竞争条件:由于您在线程上执行
GrabSomeData
,因此您需要同步对tcp::socket
和buffer
(共享资源)的访问。
io_context
itself is thread-safe.io_context
本身是线程安全的。
In this case, it's really easy to avoid, since you don't need to start the async operation until after you sent the request:在这种情况下,很容易避免,因为在发送请求之前不需要启动异步操作:
write(socket, boost::asio::buffer(sRequest)); GrabSomeData(socket);
async_read_some
has a similar problem as the write side. async_read_some
与写入端有类似的问题。 You will want a composed read operation that reads the expected output so read_until(socket, buf, "\r\n\r\n")
and then read how much content is expected based on Content-Length
header, Connection: Close
and others (think chunked encoding).您将需要一个组合读取操作来读取预期的 output so
read_until(socket, buf, "\r\n\r\n")
然后根据Content-Length
header、 Connection: Close
等读取预期的内容量(想想分块编码)。
You currently have no good way to store and access the response.您目前没有存储和访问响应的好方法。 It would be a lot easier to use a streambuf, a single composed read.
使用streambuf(单个组合读取)会容易得多。
If you want to be really solid, use Beast to receive a HTTP/1.1 response (which can even be chunked) and not worry about when it's complete (the library does it for you):如果您想真正可靠,请使用 Beast 接收 HTTP/1.1 响应(甚至可以分块),而不必担心它何时完成(库会为您完成):
auto GrabSomeData(tcp::socket& socket) { http::response<http::string_body> res; auto buf = boost::asio::dynamic_buffer(vBuffer); http::read(socket, buf, res); return res; }
Oh, and don't do it on a thread (why was that anyways? it literally just introduced undefined behavior for no gain):哦,不要在线程上这样做(为什么会这样?它实际上只是引入了未定义的行为而没有任何收获):
Compiles on MSVC: Godbolt在 MSVC 上编译:Godbolt
#include <boost/asio.hpp>
#include <boost/beast/http.hpp>
#include <iostream>
#include <iomanip>
using boost::asio::ip::tcp;
std::vector<char> vBuffer; // TODO FIXME global variable
auto GrabSomeData(tcp::socket& socket) {
namespace http = boost::beast::http;
http::response<http::string_body> res;
auto buf = boost::asio::dynamic_buffer(vBuffer);
http::read(socket, buf, res);
return res;
}
int main() try {
boost::asio::io_context context;
std::cout << "Starting " << std::endl;
tcp::endpoint endpoint(boost::asio::ip::make_address("13.107.21.200"), 80);
tcp::socket socket(context);
socket.connect(endpoint);
std::cout << "Connected" << std::endl;
std::string const sRequest = "GET /index.html HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: close\r\n"
"\r\n";
write(socket, boost::asio::buffer(sRequest));
auto response = GrabSomeData(socket);
std::cout << "Response body length: " << response.body().size() << std::endl;
std::cout << "Response headers: " << response.base() << std::endl;
std::cout << "Response body: " << std::quoted(response.body()) << std::endl;
context.run(); // run_for(10s) e.g.
} catch (boost::system::system_error const& se) {
std::cerr << "Error: " << se.code().message() << std::endl;
}
This sample printed:此示例打印:
Starting
Connected
Response body length: 194
Response headers: HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
X-MSEdge-Ref: 0BstXYAAAAACeQ2y+botzQISiBe2U3iGCQ0hHRURHRTE0MDgARWRnZQ==
Date: Sun, 21 Mar 2021 22:39:02 GMT
Connection: close
Response body: "<h2>Our services aren't available right now</h2><p>We're working to restore all services as soon as possible. Please check back soon.</p>0BstXYAAAAACeQ2y+botzQISiBe2U3iGCQ0hHRURHRTE0MDgARWRnZQ=="
NOTE It does indeed use chunked encoding, which you didn't seem to be anticipating.
注意它确实使用了分块编码,您似乎没有预料到。
Thanks @sehe for the answer and recommendations, it took so long but I've upgrade to New Windows10 and Visual Studio 2019 , and Boost 1_76 and the problem solved!感谢@sehe 的回答和建议,花了很长时间,但我已经升级到 New Windows10和Visual Studio 2019和Boost 1_76并且问题解决了!
Those errors were totally irrelevant to the code!这些错误与代码完全无关!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.