| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- #include "HttpServerImpl.h"
- #include <Logging.h>
- #include <sys/wait.h>
- #include <functional>
- #include <sstream>
- namespace Http {
- HttpServerImpl::HttpServerImpl(unsigned short port, std::function<std::string(const std::string&, const std::vector<HttpPostData>&)> callback) :
- m_threadPoolSize(3),
- m_signals(m_ioService),
- m_acceptor(m_ioService),
- m_requestHandler(callback)
- {
- m_signals.add(SIGINT);
- m_signals.add(SIGTERM);
- m_signals.add(SIGQUIT);
- m_signals.async_wait(std::bind(&HttpServerImpl::HandleStop, this));
- asio::ip::tcp::resolver resolver(m_ioService);
- asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
- m_acceptor.open(endpoint.protocol());
- m_acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true));
- m_acceptor.bind(endpoint);
- m_acceptor.listen();
- for (std::size_t i = 0; i < m_threadPoolSize; ++i)
- {
- auto thread = std::make_shared<std::thread>([&] { m_ioService.run(); });
- #ifdef __linux__
- pthread_setname_np(thread->native_handle(), "HttpServer");
- #endif
- m_threads.push_back(thread);
- }
- StartAccept();
- }
- HttpServerImpl::~HttpServerImpl()
- {
- }
- void HttpServerImpl::Wait()
- {
- for (std::size_t i = 0; i < m_threads.size(); ++i)
- m_threads[i]->join();
- }
- void HttpServerImpl::StartAccept()
- {
- m_connection.reset(new HttpConnection(m_ioService, m_requestHandler));
- m_acceptor.async_accept(m_connection->Socket(), std::bind(&HttpServerImpl::HandleAccept, this, std::placeholders::_1));
- }
- void HttpServerImpl::HandleAccept(const std::error_code& ec)
- {
- if (!ec)
- {
- m_connection->Start();
- }
- else
- {
- std::stringstream ss;
- ss << "Http Accept error: " << ec.message() << std::endl;
- Logging::Log(Logging::Severity::Error, ss.str());
- }
- StartAccept();
- }
- void HttpServerImpl::HandleStop()
- {
- m_ioService.stop();
- }
- } // namespace Http
|