http_server_small.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. //
  2. // Copyright (c) 2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. //------------------------------------------------------------------------------
  10. //
  11. // Example: HTTP server, small
  12. //
  13. //------------------------------------------------------------------------------
  14. #include <boost/beast/core.hpp>
  15. #include <boost/beast/http.hpp>
  16. #include <boost/beast/version.hpp>
  17. #include <boost/asio.hpp>
  18. #include <chrono>
  19. #include <cstdlib>
  20. #include <ctime>
  21. #include <iostream>
  22. #include <memory>
  23. #include <string>
  24. namespace beast = boost::beast; // from <boost/beast.hpp>
  25. namespace http = beast::http; // from <boost/beast/http.hpp>
  26. namespace net = boost::asio; // from <boost/asio.hpp>
  27. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  28. namespace my_program_state
  29. {
  30. std::size_t
  31. request_count()
  32. {
  33. static std::size_t count = 0;
  34. return ++count;
  35. }
  36. std::time_t
  37. now()
  38. {
  39. return std::time(0);
  40. }
  41. }
  42. class http_connection : public std::enable_shared_from_this<http_connection>
  43. {
  44. public:
  45. http_connection(tcp::socket socket)
  46. : socket_(std::move(socket))
  47. {
  48. }
  49. // Initiate the asynchronous operations associated with the connection.
  50. void
  51. start()
  52. {
  53. read_request();
  54. check_deadline();
  55. }
  56. private:
  57. // The socket for the currently connected client.
  58. tcp::socket socket_;
  59. // The buffer for performing reads.
  60. beast::flat_buffer buffer_{8192};
  61. // The request message.
  62. http::request<http::dynamic_body> request_;
  63. // The response message.
  64. http::response<http::dynamic_body> response_;
  65. // The timer for putting a deadline on connection processing.
  66. net::steady_timer deadline_{
  67. socket_.get_executor(), std::chrono::seconds(60)};
  68. // Asynchronously receive a complete request message.
  69. void
  70. read_request()
  71. {
  72. auto self = shared_from_this();
  73. http::async_read(
  74. socket_,
  75. buffer_,
  76. request_,
  77. [self](beast::error_code ec,
  78. std::size_t bytes_transferred)
  79. {
  80. boost::ignore_unused(bytes_transferred);
  81. if(!ec)
  82. self->process_request();
  83. });
  84. }
  85. // Determine what needs to be done with the request message.
  86. void
  87. process_request()
  88. {
  89. response_.version(request_.version());
  90. response_.keep_alive(false);
  91. switch(request_.method())
  92. {
  93. case http::verb::get:
  94. response_.result(http::status::ok);
  95. response_.set(http::field::server, "Beast");
  96. create_response();
  97. break;
  98. default:
  99. // We return responses indicating an error if
  100. // we do not recognize the request method.
  101. response_.result(http::status::bad_request);
  102. response_.set(http::field::content_type, "text/plain");
  103. beast::ostream(response_.body())
  104. << "Invalid request-method '"
  105. << std::string(request_.method_string())
  106. << "'";
  107. break;
  108. }
  109. write_response();
  110. }
  111. // Construct a response message based on the program state.
  112. void
  113. create_response()
  114. {
  115. if(request_.target() == "/count")
  116. {
  117. response_.set(http::field::content_type, "text/html");
  118. beast::ostream(response_.body())
  119. << "<html>\n"
  120. << "<head><title>Request count</title></head>\n"
  121. << "<body>\n"
  122. << "<h1>Request count</h1>\n"
  123. << "<p>There have been "
  124. << my_program_state::request_count()
  125. << " requests so far.</p>\n"
  126. << "</body>\n"
  127. << "</html>\n";
  128. }
  129. else if(request_.target() == "/time")
  130. {
  131. response_.set(http::field::content_type, "text/html");
  132. beast::ostream(response_.body())
  133. << "<html>\n"
  134. << "<head><title>Current time</title></head>\n"
  135. << "<body>\n"
  136. << "<h1>Current time</h1>\n"
  137. << "<p>The current time is "
  138. << my_program_state::now()
  139. << " seconds since the epoch.</p>\n"
  140. << "</body>\n"
  141. << "</html>\n";
  142. }
  143. else
  144. {
  145. response_.result(http::status::not_found);
  146. response_.set(http::field::content_type, "text/plain");
  147. beast::ostream(response_.body()) << "File not found\r\n";
  148. }
  149. }
  150. // Asynchronously transmit the response message.
  151. void
  152. write_response()
  153. {
  154. auto self = shared_from_this();
  155. response_.set(http::field::content_length, response_.body().size());
  156. http::async_write(
  157. socket_,
  158. response_,
  159. [self](beast::error_code ec, std::size_t)
  160. {
  161. self->socket_.shutdown(tcp::socket::shutdown_send, ec);
  162. self->deadline_.cancel();
  163. });
  164. }
  165. // Check whether we have spent enough time on this connection.
  166. void
  167. check_deadline()
  168. {
  169. auto self = shared_from_this();
  170. deadline_.async_wait(
  171. [self](beast::error_code ec)
  172. {
  173. if(!ec)
  174. {
  175. // Close socket to cancel any outstanding operation.
  176. self->socket_.close(ec);
  177. }
  178. });
  179. }
  180. };
  181. // "Loop" forever accepting new connections.
  182. void
  183. http_server(tcp::acceptor& acceptor, tcp::socket& socket)
  184. {
  185. acceptor.async_accept(socket,
  186. [&](beast::error_code ec)
  187. {
  188. if(!ec)
  189. std::make_shared<http_connection>(std::move(socket))->start();
  190. http_server(acceptor, socket);
  191. });
  192. }
  193. int
  194. main(int argc, char* argv[])
  195. {
  196. try
  197. {
  198. // Check command line arguments.
  199. if(argc != 3)
  200. {
  201. std::cerr << "Usage: " << argv[0] << " <address> <port>\n";
  202. std::cerr << " For IPv4, try:\n";
  203. std::cerr << " receiver 0.0.0.0 80\n";
  204. std::cerr << " For IPv6, try:\n";
  205. std::cerr << " receiver 0::0 80\n";
  206. return EXIT_FAILURE;
  207. }
  208. auto const address = net::ip::make_address(argv[1]);
  209. unsigned short port = static_cast<unsigned short>(std::atoi(argv[2]));
  210. net::io_context ioc{1};
  211. tcp::acceptor acceptor{ioc, {address, port}};
  212. tcp::socket socket{ioc};
  213. http_server(acceptor, socket);
  214. ioc.run();
  215. }
  216. catch(std::exception const& e)
  217. {
  218. std::cerr << "Error: " << e.what() << std::endl;
  219. return EXIT_FAILURE;
  220. }
  221. }