MCPcopy Create free account
hub / github.com/alibaba/async_simple / start

Function start

demo_example/http/coroutine_http/http_client.cpp:23–99  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21using asio::ip::tcp;
22
23async_simple::coro::Lazy<void> start(asio::io_context &io_context,
24 std::string host, std::string port) {
25 asio::ip::tcp::socket socket(io_context);
26 auto ec = co_await async_connect(io_context, socket, host, port);
27 if (ec) {
28 std::cout << "Connect error: " << ec.message() << '\n';
29 throw asio::system_error(ec);
30 }
31 std::cout << "Connect to " << host << ":" << port << " successfully.\n";
32
33 std::stringstream request_stream;
34 request_stream << "GET "
35 << "/"
36 << " HTTP/1.1\r\n";
37 request_stream << "Host: "
38 << "127.0.0.1"
39 << "\r\n";
40 request_stream << "Accept: */*\r\n";
41 request_stream << "Connection: close\r\n\r\n";
42
43 // Send the request.
44 co_await async_write(socket, asio::buffer(request_stream.str(),
45 request_stream.str().size()));
46
47 // Read the response status line. The response streambuf will automatically
48 // grow to accommodate the entire line. The growth may be limited by passing
49 // a maximum size to the streambuf constructor.
50 asio::streambuf response;
51 co_await async_read_until(socket, response, "\r\n");
52
53 // Check that response is OK.
54 std::istream response_stream(&response);
55 std::string http_version;
56 response_stream >> http_version;
57 unsigned int status_code;
58 response_stream >> status_code;
59 std::string status_message;
60 std::getline(response_stream, status_message);
61 if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
62 std::cout << "Invalid response\n";
63 co_return;
64 }
65 if (status_code != 200) {
66 std::cout << "Response returned with status code " << status_code
67 << "\n";
68 co_return;
69 }
70
71 // Read the response headers, which are terminated by a blank line.
72 co_await async_read_until(socket, response, "\r\n\r\n");
73
74 // Process the response headers.
75 std::string header;
76 while (std::getline(response_stream, header) && header != "\r")
77 std::cout << header << "\n";
78 std::cout << "\n";
79
80 // Write whatever content we already have to output.

Calls 9

system_errorClass · 0.85
messageMethod · 0.80
async_connectFunction · 0.50
async_writeFunction · 0.50
bufferFunction · 0.50
async_read_untilFunction · 0.50
async_readFunction · 0.50
sizeMethod · 0.45
shutdownMethod · 0.45

Tested by

no test coverage detected