aboutsummaryrefslogtreecommitdiffstats
path: root/include/http_server.h
diff options
context:
space:
mode:
authoripknHama <ipknhama@gmail.com>2014-08-07 01:18:33 +0900
committeripknHama <ipknhama@gmail.com>2014-08-07 01:18:33 +0900
commit031615ac866cc3c8f1900dd4b4aae2106ad31230 (patch)
treeb8b7206ffbd2043368580ec269c97436929fe452 /include/http_server.h
parenta0c93f5b84cc11b30bc6320ac26127832ef8bf7a (diff)
downloadcrow-031615ac866cc3c8f1900dd4b4aae2106ad31230.tar.gz
crow-031615ac866cc3c8f1900dd4b4aae2106ad31230.zip
source resturcturing + CMake
Diffstat (limited to 'include/http_server.h')
-rw-r--r--include/http_server.h81
1 files changed, 81 insertions, 0 deletions
diff --git a/include/http_server.h b/include/http_server.h
new file mode 100644
index 0000000..9381fdb
--- /dev/null
+++ b/include/http_server.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include <boost/asio.hpp>
+#include <cstdint>
+#include <atomic>
+
+#include <memory>
+
+#include "http_connection.h"
+#include "datetime.h"
+#include "logging.h"
+
+namespace crow
+{
+ using namespace boost;
+ using tcp = asio::ip::tcp;
+
+ template <typename Handler>
+ class Server
+ {
+ public:
+ Server(Handler* handler, uint16_t port, uint16_t concurrency = 1)
+ : acceptor_(io_service_, tcp::endpoint(asio::ip::address(), port)),
+ socket_(io_service_),
+ signals_(io_service_, SIGINT, SIGTERM),
+ handler_(handler),
+ concurrency_(concurrency),
+ port_(port)
+ {
+ do_accept();
+ }
+
+ void run()
+ {
+ std::vector<std::future<void>> v;
+ for(uint16_t i = 0; i < concurrency_; i ++)
+ v.push_back(
+ std::async(std::launch::async, [this]{io_service_.run();})
+ );
+
+ CROW_LOG_INFO << server_name_ << " server is running, local port " << port_;
+
+ signals_.async_wait(
+ [&](const boost::system::error_code& error, int signal_number){
+ io_service_.stop();
+ });
+
+ }
+
+ void stop()
+ {
+ io_service_.stop();
+ }
+
+ private:
+ void do_accept()
+ {
+ acceptor_.async_accept(socket_,
+ [this](boost::system::error_code ec)
+ {
+ if (!ec)
+ {
+ auto p = std::make_shared<Connection<Handler>>(std::move(socket_), handler_, server_name_);
+ p->start();
+ }
+ do_accept();
+ });
+ }
+
+ private:
+ asio::io_service io_service_;
+ tcp::acceptor acceptor_;
+ tcp::socket socket_;
+ boost::asio::signal_set signals_;
+
+ Handler* handler_;
+ uint16_t concurrency_{1};
+ std::string server_name_ = "Crow/0.1";
+ uint16_t port_;
+ };
+}