aboutsummaryrefslogtreecommitdiffstats
path: root/http_server.h
blob: 002eec68df9ee1b32f63e551efc0a92a76d53663 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once

#include <boost/asio.hpp>
#include <stdint.h>

#include "http_connection.h"

// TEST
#include <iostream>

namespace flask
{
    using namespace boost;
    using tcp = asio::ip::tcp;
    template <typename Handler>
    class Server
    {
    public:
        Server(Handler* handler, uint16_t port)
            : acceptor_(io_service_, tcp::endpoint(asio::ip::address(), port)), socket_(io_service_), handler_(handler)
        {
            do_accept();
        }

        void run()
        {
            auto _ = std::async(std::launch::async, [this]{io_service_.run();});
        }

    private:
        void do_accept()
        {
            acceptor_.async_accept(socket_, 
                [this](boost::system::error_code ec)
                {
                    if (!ec)
                        (new Connection<Handler>(std::move(socket_), handler_))->start();
                    do_accept();
                });
        }

    private:
        asio::io_service io_service_;
        tcp::acceptor acceptor_;
        tcp::socket socket_;
        Handler* handler_;
    };
}