MCPcopy Create free account
hub / github.com/boostorg/asio / main

Function main

example/cpp11/http/client/sync_client.cpp:19–106  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17using boost::asio::ip::tcp;
18
19int main(int argc, char* argv[])
20{
21 try
22 {
23 if (argc != 3)
24 {
25 std::cout << "Usage: sync_client <server> <path>\n";
26 std::cout << "Example:\n";
27 std::cout << " sync_client www.boost.org /LICENSE_1_0.txt\n";
28 return 1;
29 }
30
31 boost::asio::io_context io_context;
32
33 // Get a list of endpoints corresponding to the server name.
34 tcp::resolver resolver(io_context);
35 tcp::resolver::results_type endpoints = resolver.resolve(argv[1], "http");
36
37 // Try each endpoint until we successfully establish a connection.
38 tcp::socket socket(io_context);
39 boost::asio::connect(socket, endpoints);
40
41 // Form the request. We specify the "Connection: close" header so that the
42 // server will close the socket after transmitting the response. This will
43 // allow us to treat all data up until the EOF as the content.
44 boost::asio::streambuf request;
45 std::ostream request_stream(&request);
46 request_stream << "GET " << argv[2] << " HTTP/1.0\r\n";
47 request_stream << "Host: " << argv[1] << "\r\n";
48 request_stream << "Accept: */*\r\n";
49 request_stream << "Connection: close\r\n\r\n";
50
51 // Send the request.
52 boost::asio::write(socket, request);
53
54 // Read the response status line. The response streambuf will automatically
55 // grow to accommodate the entire line. The growth may be limited by passing
56 // a maximum size to the streambuf constructor.
57 boost::asio::streambuf response;
58 boost::asio::read_until(socket, response, "\r\n");
59
60 // Check that response is OK.
61 std::istream response_stream(&response);
62 std::string http_version;
63 response_stream >> http_version;
64 unsigned int status_code;
65 response_stream >> status_code;
66 std::string status_message;
67 std::getline(response_stream, status_message);
68 if (!response_stream || http_version.substr(0, 5) != "HTTP/")
69 {
70 std::cout << "Invalid response\n";
71 return 1;
72 }
73 if (status_code != 200)
74 {
75 std::cout << "Response returned with status code " << status_code << "\n";
76 return 1;

Callers

nothing calls this directly

Calls 7

writeFunction · 0.85
read_untilFunction · 0.85
readFunction · 0.85
transfer_at_leastFunction · 0.85
connectFunction · 0.50
resolveMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected