-
Notifications
You must be signed in to change notification settings - Fork 2
/
02_blocking_function.cpp
37 lines (35 loc) · 1007 Bytes
/
02_blocking_function.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// get_robotstxt() is a blocking function to download and output the file
// robots.txt from a webserver; hostname is passed as only parameter
#include <boost/asio.hpp>
#include <string>
#include <sstream>
#include <iostream>
void get_robotstxt(const std::string &host)
{
using namespace boost::asio;
io_service ioservice;
ip::tcp::resolver resolver(ioservice);
ip::tcp::resolver::query query(host, "http");
auto it = resolver.resolve(query);
ip::tcp::socket socket(ioservice);
socket.connect(*it);
std::string request = "GET /robots.txt HTTP/1.1\r\nHost: " + host + "\r\n\r\n";
write(socket, buffer(request));
streambuf response;
boost::system::error_code ec;
read(socket, response, transfer_all(), ec);
if (ec == error::eof)
{
std::ostringstream os;
os << &response;
std::string s = os.str();
std::size_t idx = s.find("\r\n\r\n");
if (idx != std::string::npos)
s.erase(0, idx + 4);
std::cout << s;
}
}
int main()
{
get_robotstxt("theboostcpplibraries.com"); // blocking
}