Samchon Framework for CPP  1.0.0
IServer.cpp
1 #pragma once
2 #include <samchon/protocol/IServer.hpp>
3 
4 #include <memory>
5 #include <mutex>
6 #include <thread>
7 #include <boost/asio.hpp>
8 
9 using namespace samchon;
10 using namespace samchon::protocol;
11 
12 using namespace std;
13 using namespace boost::asio;
14 using namespace boost::asio::ip;
15 
16 auto IServer::MY_IP() const -> std::string { return ""; }
17 
19 {
20  acceptor = nullptr;
21 }
22 IServer::~IServer()
23 {
24  close();
25 
26  if (acceptor != nullptr)
27  delete acceptor;
28 }
29 
31 {
32  if (acceptor != nullptr && acceptor->is_open() == true)
33  return;
34 
35  boost::system::error_code error;
36  io_service ioService;
37  unique_ptr<tcp::endpoint> endPoint;
38 
39  if (acceptor == nullptr)
40  {
41  string &myIP = MY_IP();
42 
43  if (myIP.empty() == true)
44  endPoint.reset( new tcp::endpoint(tcp::v4(), PORT()) );
45  else
46  endPoint.reset( new tcp::endpoint( address::from_string(myIP), PORT() ) );
47 
48  acceptor = new tcp::acceptor(ioService, *endPoint);
49  }
50 
51  while (true)
52  {
53  tcp::socket *socket = new tcp::socket(ioService);
54  acceptor->accept(*socket, error);
55 
56  if (error)
57  {
58  delete socket;
59  break;
60  }
61  thread(&IServer::addClient, this, socket).detach();
62  }
63  delete acceptor;
64  acceptor = nullptr;
65 }
66 
68 {
69  if (acceptor == nullptr)
70  return;
71 
72  acceptor->cancel();
73  acceptor->close();
74 }
virtual void close()
Close the server.
Definition: IServer.cpp:67
Definition: RWMutex.hpp:4
virtual auto MY_IP() const -> std::string
(optional) Server&#39;s IP
Definition: IServer.cpp:16
Package of network protocol and libraries.
Definition: protocol.hpp:185
IServer()
Default Constructor.
Definition: IServer.cpp:18
virtual void addClient(Socket *)=0
Handling connection of a physical client.
virtual void open()
Open the server.
Definition: IServer.cpp:30
Top level namespace of products built from samchon.
Definition: ByteArray.hpp:7