| 317 | } |
| 318 | |
| 319 | int main(int argc, char* argv[]) |
| 320 | { |
| 321 | // Check command line arguments. |
| 322 | if (argc != 5) |
| 323 | { |
| 324 | std::cerr << |
| 325 | "Usage: http-server-coro <address> <port> <doc_root> <threads>\n" << |
| 326 | "Example:\n" << |
| 327 | " http-server-coro 0.0.0.0 8080 . 1\n"; |
| 328 | return EXIT_FAILURE; |
| 329 | } |
| 330 | auto const address = net::ip::make_address(argv[1]); |
| 331 | auto const port = static_cast<unsigned short>(std::atoi(argv[2])); |
| 332 | auto const doc_root = std::make_shared<std::string>(argv[3]); |
| 333 | auto const threads = std::max<int>(1, std::atoi(argv[4])); |
| 334 | |
| 335 | // The io_context is required for all I/O |
| 336 | net::io_context ioc{threads}; |
| 337 | |
| 338 | // Spawn a listening port |
| 339 | boost::asio::spawn(ioc, |
| 340 | std::bind( |
| 341 | &do_listen, |
| 342 | std::ref(ioc), |
| 343 | tcp::endpoint{address, port}, |
| 344 | doc_root, |
| 345 | std::placeholders::_1), |
| 346 | // on completion, spawn will call this function |
| 347 | [](std::exception_ptr ex) |
| 348 | { |
| 349 | // if an exception occurred in the coroutine, |
| 350 | // it's something critical, e.g. out of memory |
| 351 | // we capture normal errors in the ec |
| 352 | // so we just rethrow the exception here, |
| 353 | // which will cause `ioc.run()` to throw |
| 354 | if (ex) |
| 355 | std::rethrow_exception(ex); |
| 356 | }); |
| 357 | |
| 358 | // Run the I/O service on the requested number of threads |
| 359 | std::vector<std::thread> v; |
| 360 | v.reserve(threads - 1); |
| 361 | for(auto i = threads - 1; i > 0; --i) |
| 362 | v.emplace_back( |
| 363 | [&ioc] |
| 364 | { |
| 365 | ioc.run(); |
| 366 | }); |
| 367 | ioc.run(); |
| 368 | |
| 369 | return EXIT_SUCCESS; |
| 370 | } |