Samchon Framework for CPP  1.0.0
Server.hpp
1 #pragma once
2 #include <samchon/API.hpp>
3 
4 #include <samchon/protocol/ClientDriver.hpp>
5 
6 #include <thread>
7 
8 namespace samchon
9 {
10 namespace protocol
11 {
45  class Server
46  {
47  protected:
48  std::unique_ptr<boost::asio::ip::tcp::acceptor> _Acceptor;
49 
50  public:
55  {
56  };
57 
61  virtual ~Server()
62  {
63  if (_Acceptor == nullptr || _Acceptor->is_open() == false)
64  return;
65 
66  close();
67  };
68 
74  virtual void open(int port)
75  {
76  if (_Acceptor != nullptr && _Acceptor->is_open())
77  return;
78 
79  boost::asio::io_service io_service;
80  boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
81  boost::system::error_code error;
82 
83  _Acceptor.reset(new boost::asio::ip::tcp::acceptor(io_service, endpoint));
84 
85  while (true)
86  {
87  std::shared_ptr<boost::asio::ip::tcp::socket> socket(new boost::asio::ip::tcp::socket(io_service));
88  _Acceptor->accept(*socket);
89 
90  if (error)
91  break;
92 
93  std::thread(&Server::handle_connection, this, socket).detach();
94  }
95  };
96 
100  virtual void close()
101  {
102  if (_Acceptor == nullptr)
103  return;
104 
105  _Acceptor->cancel();
106  _Acceptor->close();
107  };
108 
109  protected:
127  virtual void addClient(std::shared_ptr<ClientDriver>) = 0; //ADD_CLIENT
128 
129  private:
130  virtual void handle_connection(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
131  {
132  addClient(std::make_shared<ClientDriver>(socket));
133  };
134  };
135 };
136 };
virtual void addClient(std::shared_ptr< ClientDriver >)=0
virtual void open(int port)
Definition: Server.hpp:74
virtual void close()
Definition: Server.hpp:100