server.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //
  2. // server.cpp
  3. // ~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #include <array>
  11. #include <cstdlib>
  12. #include <iostream>
  13. #include <memory>
  14. #include <type_traits>
  15. #include <utility>
  16. #include <boost/asio.hpp>
  17. using boost::asio::ip::tcp;
  18. // Class to manage the memory to be used for handler-based custom allocation.
  19. // It contains a single block of memory which may be returned for allocation
  20. // requests. If the memory is in use when an allocation request is made, the
  21. // allocator delegates allocation to the global heap.
  22. class handler_memory
  23. {
  24. public:
  25. handler_memory()
  26. : in_use_(false)
  27. {
  28. }
  29. handler_memory(const handler_memory&) = delete;
  30. handler_memory& operator=(const handler_memory&) = delete;
  31. void* allocate(std::size_t size)
  32. {
  33. if (!in_use_ && size < sizeof(storage_))
  34. {
  35. in_use_ = true;
  36. return &storage_;
  37. }
  38. else
  39. {
  40. return ::operator new(size);
  41. }
  42. }
  43. void deallocate(void* pointer)
  44. {
  45. if (pointer == &storage_)
  46. {
  47. in_use_ = false;
  48. }
  49. else
  50. {
  51. ::operator delete(pointer);
  52. }
  53. }
  54. private:
  55. // Storage space used for handler-based custom memory allocation.
  56. typename std::aligned_storage<1024>::type storage_;
  57. // Whether the handler-based custom allocation storage has been used.
  58. bool in_use_;
  59. };
  60. // The allocator to be associated with the handler objects. This allocator only
  61. // needs to satisfy the C++11 minimal allocator requirements.
  62. template <typename T>
  63. class handler_allocator
  64. {
  65. public:
  66. using value_type = T;
  67. explicit handler_allocator(handler_memory& mem)
  68. : memory_(mem)
  69. {
  70. }
  71. template <typename U>
  72. handler_allocator(const handler_allocator<U>& other) noexcept
  73. : memory_(other.memory_)
  74. {
  75. }
  76. bool operator==(const handler_allocator& other) const noexcept
  77. {
  78. return &memory_ == &other.memory_;
  79. }
  80. bool operator!=(const handler_allocator& other) const noexcept
  81. {
  82. return &memory_ != &other.memory_;
  83. }
  84. T* allocate(std::size_t n) const
  85. {
  86. return static_cast<T*>(memory_.allocate(sizeof(T) * n));
  87. }
  88. void deallocate(T* p, std::size_t /*n*/) const
  89. {
  90. return memory_.deallocate(p);
  91. }
  92. private:
  93. template <typename> friend class handler_allocator;
  94. // The underlying memory.
  95. handler_memory& memory_;
  96. };
  97. // Wrapper class template for handler objects to allow handler memory
  98. // allocation to be customised. The allocator_type type and get_allocator()
  99. // member function are used by the asynchronous operations to obtain the
  100. // allocator. Calls to operator() are forwarded to the encapsulated handler.
  101. template <typename Handler>
  102. class custom_alloc_handler
  103. {
  104. public:
  105. using allocator_type = handler_allocator<Handler>;
  106. custom_alloc_handler(handler_memory& m, Handler h)
  107. : memory_(m),
  108. handler_(h)
  109. {
  110. }
  111. allocator_type get_allocator() const noexcept
  112. {
  113. return allocator_type(memory_);
  114. }
  115. template <typename ...Args>
  116. void operator()(Args&&... args)
  117. {
  118. handler_(std::forward<Args>(args)...);
  119. }
  120. private:
  121. handler_memory& memory_;
  122. Handler handler_;
  123. };
  124. // Helper function to wrap a handler object to add custom allocation.
  125. template <typename Handler>
  126. inline custom_alloc_handler<Handler> make_custom_alloc_handler(
  127. handler_memory& m, Handler h)
  128. {
  129. return custom_alloc_handler<Handler>(m, h);
  130. }
  131. class session
  132. : public std::enable_shared_from_this<session>
  133. {
  134. public:
  135. session(tcp::socket socket)
  136. : socket_(std::move(socket))
  137. {
  138. }
  139. void start()
  140. {
  141. do_read();
  142. }
  143. private:
  144. void do_read()
  145. {
  146. auto self(shared_from_this());
  147. socket_.async_read_some(boost::asio::buffer(data_),
  148. make_custom_alloc_handler(handler_memory_,
  149. [this, self](boost::system::error_code ec, std::size_t length)
  150. {
  151. if (!ec)
  152. {
  153. do_write(length);
  154. }
  155. }));
  156. }
  157. void do_write(std::size_t length)
  158. {
  159. auto self(shared_from_this());
  160. boost::asio::async_write(socket_, boost::asio::buffer(data_, length),
  161. make_custom_alloc_handler(handler_memory_,
  162. [this, self](boost::system::error_code ec, std::size_t /*length*/)
  163. {
  164. if (!ec)
  165. {
  166. do_read();
  167. }
  168. }));
  169. }
  170. // The socket used to communicate with the client.
  171. tcp::socket socket_;
  172. // Buffer used to store data received from the client.
  173. std::array<char, 1024> data_;
  174. // The memory to use for handler-based custom memory allocation.
  175. handler_memory handler_memory_;
  176. };
  177. class server
  178. {
  179. public:
  180. server(boost::asio::io_context& io_context, short port)
  181. : acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
  182. {
  183. do_accept();
  184. }
  185. private:
  186. void do_accept()
  187. {
  188. acceptor_.async_accept(
  189. [this](boost::system::error_code ec, tcp::socket socket)
  190. {
  191. if (!ec)
  192. {
  193. std::make_shared<session>(std::move(socket))->start();
  194. }
  195. do_accept();
  196. });
  197. }
  198. tcp::acceptor acceptor_;
  199. };
  200. int main(int argc, char* argv[])
  201. {
  202. try
  203. {
  204. if (argc != 2)
  205. {
  206. std::cerr << "Usage: server <port>\n";
  207. return 1;
  208. }
  209. boost::asio::io_context io_context;
  210. server s(io_context, std::atoi(argv[1]));
  211. io_context.run();
  212. }
  213. catch (std::exception& e)
  214. {
  215. std::cerr << "Exception: " << e.what() << "\n";
  216. }
  217. return 0;
  218. }