2014-03-31 16:51:50 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <boost/asio.hpp>
|
2014-07-08 09:31:52 +00:00
|
|
|
#include <cstdint>
|
2014-05-02 05:17:49 +00:00
|
|
|
#include <atomic>
|
2014-03-31 16:51:50 +00:00
|
|
|
|
2014-07-29 11:20:50 +00:00
|
|
|
#include <memory>
|
|
|
|
|
2014-03-31 16:51:50 +00:00
|
|
|
#include "http_connection.h"
|
2014-05-02 05:17:49 +00:00
|
|
|
#include "datetime.h"
|
2014-05-20 16:17:56 +00:00
|
|
|
#include "logging.h"
|
2014-03-31 16:51:50 +00:00
|
|
|
|
2014-04-26 17:19:59 +00:00
|
|
|
namespace crow
|
2014-03-31 16:51:50 +00:00
|
|
|
{
|
|
|
|
using namespace boost;
|
|
|
|
using tcp = asio::ip::tcp;
|
2014-07-08 09:31:52 +00:00
|
|
|
|
2014-03-31 16:51:50 +00:00
|
|
|
template <typename Handler>
|
|
|
|
class Server
|
|
|
|
{
|
|
|
|
public:
|
2014-04-17 06:50:28 +00:00
|
|
|
Server(Handler* handler, uint16_t port, uint16_t concurrency = 1)
|
2014-05-02 05:17:49 +00:00
|
|
|
: acceptor_(io_service_, tcp::endpoint(asio::ip::address(), port)),
|
|
|
|
socket_(io_service_),
|
|
|
|
signals_(io_service_, SIGINT, SIGTERM),
|
|
|
|
handler_(handler),
|
2014-05-20 16:17:56 +00:00
|
|
|
concurrency_(concurrency),
|
|
|
|
port_(port)
|
2014-03-31 16:51:50 +00:00
|
|
|
{
|
|
|
|
do_accept();
|
|
|
|
}
|
|
|
|
|
|
|
|
void run()
|
|
|
|
{
|
2014-04-17 06:50:28 +00:00
|
|
|
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();})
|
|
|
|
);
|
2014-05-02 05:17:49 +00:00
|
|
|
|
2014-05-20 22:30:51 +00:00
|
|
|
CROW_LOG_INFO << server_name_ << " server is running, local port " << port_;
|
2014-05-20 16:17:56 +00:00
|
|
|
|
2014-05-02 05:17:49 +00:00
|
|
|
signals_.async_wait(
|
|
|
|
[&](const boost::system::error_code& error, int signal_number){
|
|
|
|
io_service_.stop();
|
|
|
|
});
|
|
|
|
|
2014-03-31 16:51:50 +00:00
|
|
|
}
|
|
|
|
|
2014-04-15 13:08:23 +00:00
|
|
|
void stop()
|
|
|
|
{
|
|
|
|
io_service_.stop();
|
|
|
|
}
|
|
|
|
|
2014-03-31 16:51:50 +00:00
|
|
|
private:
|
|
|
|
void do_accept()
|
|
|
|
{
|
|
|
|
acceptor_.async_accept(socket_,
|
|
|
|
[this](boost::system::error_code ec)
|
|
|
|
{
|
|
|
|
if (!ec)
|
2014-07-29 11:20:50 +00:00
|
|
|
{
|
|
|
|
auto p = std::make_shared<Connection<Handler>>(std::move(socket_), handler_, server_name_);
|
|
|
|
p->start();
|
|
|
|
}
|
2014-03-31 16:51:50 +00:00
|
|
|
do_accept();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
asio::io_service io_service_;
|
|
|
|
tcp::acceptor acceptor_;
|
|
|
|
tcp::socket socket_;
|
2014-05-02 05:17:49 +00:00
|
|
|
boost::asio::signal_set signals_;
|
|
|
|
|
2014-03-31 16:51:50 +00:00
|
|
|
Handler* handler_;
|
2014-05-02 09:22:02 +00:00
|
|
|
uint16_t concurrency_{1};
|
2014-05-02 05:17:49 +00:00
|
|
|
std::string server_name_ = "Crow/0.1";
|
2014-05-20 16:17:56 +00:00
|
|
|
uint16_t port_;
|
2014-03-31 16:51:50 +00:00
|
|
|
};
|
|
|
|
}
|