HttpServerImpl.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "HttpServerImpl.h"
  2. #include <Logging.h>
  3. #include <sys/wait.h>
  4. #include <functional>
  5. #include <sstream>
  6. namespace Http {
  7. HttpServerImpl::HttpServerImpl(unsigned short port, std::function<std::string(const std::string&, const std::vector<HttpPostData>&)> callback) :
  8. m_threadPoolSize(3),
  9. m_signals(m_ioService),
  10. m_acceptor(m_ioService),
  11. m_requestHandler(callback)
  12. {
  13. m_signals.add(SIGINT);
  14. m_signals.add(SIGTERM);
  15. m_signals.add(SIGQUIT);
  16. m_signals.async_wait(std::bind(&HttpServerImpl::HandleStop, this));
  17. asio::ip::tcp::resolver resolver(m_ioService);
  18. asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
  19. m_acceptor.open(endpoint.protocol());
  20. m_acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true));
  21. m_acceptor.bind(endpoint);
  22. m_acceptor.listen();
  23. for (std::size_t i = 0; i < m_threadPoolSize; ++i)
  24. {
  25. auto thread = std::make_shared<std::thread>([&] { m_ioService.run(); });
  26. #ifdef __linux__
  27. pthread_setname_np(thread->native_handle(), "HttpServer");
  28. #endif
  29. m_threads.push_back(thread);
  30. }
  31. StartAccept();
  32. }
  33. HttpServerImpl::~HttpServerImpl()
  34. {
  35. }
  36. void HttpServerImpl::Wait()
  37. {
  38. for (std::size_t i = 0; i < m_threads.size(); ++i)
  39. m_threads[i]->join();
  40. }
  41. void HttpServerImpl::StartAccept()
  42. {
  43. m_connection.reset(new HttpConnection(m_ioService, m_requestHandler));
  44. m_acceptor.async_accept(m_connection->Socket(), std::bind(&HttpServerImpl::HandleAccept, this, std::placeholders::_1));
  45. }
  46. void HttpServerImpl::HandleAccept(const std::error_code& ec)
  47. {
  48. if (!ec)
  49. {
  50. m_connection->Start();
  51. }
  52. else
  53. {
  54. std::stringstream ss;
  55. ss << "Http Accept error: " << ec.message() << std::endl;
  56. Logging::Log(Logging::Severity::Error, ss.str());
  57. }
  58. StartAccept();
  59. }
  60. void HttpServerImpl::HandleStop()
  61. {
  62. m_ioService.stop();
  63. }
  64. } // namespace Http