composed_6.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // composed_6.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 <boost/asio/executor_work_guard.hpp>
  11. #include <boost/asio/io_context.hpp>
  12. #include <boost/asio/ip/tcp.hpp>
  13. #include <boost/asio/steady_timer.hpp>
  14. #include <boost/asio/use_future.hpp>
  15. #include <boost/asio/write.hpp>
  16. #include <functional>
  17. #include <iostream>
  18. #include <memory>
  19. #include <sstream>
  20. #include <string>
  21. #include <type_traits>
  22. #include <utility>
  23. using boost::asio::ip::tcp;
  24. // NOTE: This example requires the new boost::asio::async_initiate function. For
  25. // an example that works with the Networking TS style of completion tokens,
  26. // please see an older version of asio.
  27. //------------------------------------------------------------------------------
  28. // This composed operation shows composition of multiple underlying operations.
  29. // It automatically serialises a message, using its I/O streams insertion
  30. // operator, before sending it N times on the socket. To do this, it must
  31. // allocate a buffer for the encoded message and ensure this buffer's validity
  32. // until all underlying async_write operation complete. A one second delay is
  33. // inserted prior to each write operation, using a steady_timer.
  34. template <typename T, typename CompletionToken>
  35. auto async_write_messages(tcp::socket& socket,
  36. const T& message, std::size_t repeat_count,
  37. CompletionToken&& token)
  38. // The return type of the initiating function is deduced from the combination
  39. // of CompletionToken type and the completion handler's signature. When the
  40. // completion token is a simple callback, the return type is always void.
  41. // In this example, when the completion token is boost::asio::yield_context
  42. // (used for stackful coroutines) the return type would be also be void, as
  43. // there is no non-error argument to the completion handler. When the
  44. // completion token is boost::asio::use_future it would be std::future<void>.
  45. //
  46. // In C++14 we can omit the return type as it is automatically deduced from
  47. // the return type of boost::asio::async_initiate.
  48. {
  49. // In addition to determining the mechanism by which an asynchronous
  50. // operation delivers its result, a completion token also determines the time
  51. // when the operation commences. For example, when the completion token is a
  52. // simple callback the operation commences before the initiating function
  53. // returns. However, if the completion token's delivery mechanism uses a
  54. // future, we might instead want to defer initiation of the operation until
  55. // the returned future object is waited upon.
  56. //
  57. // To enable this, when implementing an asynchronous operation we must
  58. // package the initiation step as a function object. The initiation function
  59. // object's call operator is passed the concrete completion handler produced
  60. // by the completion token. This completion handler matches the asynchronous
  61. // operation's completion handler signature, which in this example is:
  62. //
  63. // void(boost::system::error_code error)
  64. //
  65. // The initiation function object also receives any additional arguments
  66. // required to start the operation. (Note: We could have instead passed these
  67. // arguments in the lambda capture set. However, we should prefer to
  68. // propagate them as function call arguments as this allows the completion
  69. // token to optimise how they are passed. For example, a lazy future which
  70. // defers initiation would need to make a decay-copy of the arguments, but
  71. // when using a simple callback the arguments can be trivially forwarded
  72. // straight through.)
  73. auto initiation = [](auto&& completion_handler, tcp::socket& socket,
  74. std::unique_ptr<std::string> encoded_message, std::size_t repeat_count,
  75. std::unique_ptr<boost::asio::steady_timer> delay_timer)
  76. {
  77. // In this example, the composed operation's intermediate completion
  78. // handler is implemented as a hand-crafted function object.
  79. struct intermediate_completion_handler
  80. {
  81. // The intermediate completion handler holds a reference to the socket as
  82. // it is used for multiple async_write operations, as well as for
  83. // obtaining the I/O executor (see get_executor below).
  84. tcp::socket& socket_;
  85. // The allocated buffer for the encoded message. The std::unique_ptr
  86. // smart pointer is move-only, and as a consequence our intermediate
  87. // completion handler is also move-only.
  88. std::unique_ptr<std::string> encoded_message_;
  89. // The repeat count remaining.
  90. std::size_t repeat_count_;
  91. // A steady timer used for introducing a delay.
  92. std::unique_ptr<boost::asio::steady_timer> delay_timer_;
  93. // To manage the cycle between the multiple underlying asychronous
  94. // operations, our intermediate completion handler is implemented as a
  95. // state machine.
  96. enum { starting, waiting, writing } state_;
  97. // As our composed operation performs multiple underlying I/O operations,
  98. // we should maintain a work object against the I/O executor. This tells
  99. // the I/O executor that there is still more work to come in the future.
  100. boost::asio::executor_work_guard<tcp::socket::executor_type> io_work_;
  101. // The user-supplied completion handler, called once only on completion
  102. // of the entire composed operation.
  103. typename std::decay<decltype(completion_handler)>::type handler_;
  104. // By having a default value for the second argument, this function call
  105. // operator matches the completion signature of both the async_write and
  106. // steady_timer::async_wait operations.
  107. void operator()(const boost::system::error_code& error, std::size_t = 0)
  108. {
  109. if (!error)
  110. {
  111. switch (state_)
  112. {
  113. case starting:
  114. case writing:
  115. if (repeat_count_ > 0)
  116. {
  117. --repeat_count_;
  118. state_ = waiting;
  119. delay_timer_->expires_after(std::chrono::seconds(1));
  120. delay_timer_->async_wait(std::move(*this));
  121. return; // Composed operation not yet complete.
  122. }
  123. break; // Composed operation complete, continue below.
  124. case waiting:
  125. state_ = writing;
  126. boost::asio::async_write(socket_,
  127. boost::asio::buffer(*encoded_message_), std::move(*this));
  128. return; // Composed operation not yet complete.
  129. }
  130. }
  131. // This point is reached only on completion of the entire composed
  132. // operation.
  133. // We no longer have any future work coming for the I/O executor.
  134. io_work_.reset();
  135. // Deallocate the encoded message before calling the user-supplied
  136. // completion handler.
  137. encoded_message_.reset();
  138. // Call the user-supplied handler with the result of the operation.
  139. handler_(error);
  140. }
  141. // It is essential to the correctness of our composed operation that we
  142. // preserve the executor of the user-supplied completion handler. With a
  143. // hand-crafted function object we can do this by defining a nested type
  144. // executor_type and member function get_executor. These obtain the
  145. // completion handler's associated executor, and default to the I/O
  146. // executor - in this case the executor of the socket - if the completion
  147. // handler does not have its own.
  148. using executor_type = boost::asio::associated_executor_t<
  149. typename std::decay<decltype(completion_handler)>::type,
  150. tcp::socket::executor_type>;
  151. executor_type get_executor() const noexcept
  152. {
  153. return boost::asio::get_associated_executor(
  154. handler_, socket_.get_executor());
  155. }
  156. // Although not necessary for correctness, we may also preserve the
  157. // allocator of the user-supplied completion handler. This is achieved by
  158. // defining a nested type allocator_type and member function
  159. // get_allocator. These obtain the completion handler's associated
  160. // allocator, and default to std::allocator<void> if the completion
  161. // handler does not have its own.
  162. using allocator_type = boost::asio::associated_allocator_t<
  163. typename std::decay<decltype(completion_handler)>::type,
  164. std::allocator<void>>;
  165. allocator_type get_allocator() const noexcept
  166. {
  167. return boost::asio::get_associated_allocator(
  168. handler_, std::allocator<void>{});
  169. }
  170. };
  171. // Initiate the underlying async_write operation using our intermediate
  172. // completion handler.
  173. auto encoded_message_buffer = boost::asio::buffer(*encoded_message);
  174. boost::asio::async_write(socket, encoded_message_buffer,
  175. intermediate_completion_handler{
  176. socket, std::move(encoded_message),
  177. repeat_count, std::move(delay_timer),
  178. intermediate_completion_handler::starting,
  179. boost::asio::make_work_guard(socket.get_executor()),
  180. std::forward<decltype(completion_handler)>(completion_handler)});
  181. };
  182. // Encode the message and copy it into an allocated buffer. The buffer will
  183. // be maintained for the lifetime of the composed asynchronous operation.
  184. std::ostringstream os;
  185. os << message;
  186. std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
  187. // Create a steady_timer to be used for the delay between messages.
  188. std::unique_ptr<boost::asio::steady_timer> delay_timer(
  189. new boost::asio::steady_timer(socket.get_executor()));
  190. // The boost::asio::async_initiate function takes:
  191. //
  192. // - our initiation function object,
  193. // - the completion token,
  194. // - the completion handler signature, and
  195. // - any additional arguments we need to initiate the operation.
  196. //
  197. // It then asks the completion token to create a completion handler (i.e. a
  198. // callback) with the specified signature, and invoke the initiation function
  199. // object with this completion handler as well as the additional arguments.
  200. // The return value of async_initiate is the result of our operation's
  201. // initiating function.
  202. //
  203. // Note that we wrap non-const reference arguments in std::reference_wrapper
  204. // to prevent incorrect decay-copies of these objects.
  205. return boost::asio::async_initiate<
  206. CompletionToken, void(boost::system::error_code)>(
  207. initiation, token, std::ref(socket),
  208. std::move(encoded_message), repeat_count,
  209. std::move(delay_timer));
  210. }
  211. //------------------------------------------------------------------------------
  212. void test_callback()
  213. {
  214. boost::asio::io_context io_context;
  215. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  216. tcp::socket socket = acceptor.accept();
  217. // Test our asynchronous operation using a lambda as a callback.
  218. async_write_messages(socket, "Testing callback\r\n", 5,
  219. [](const boost::system::error_code& error)
  220. {
  221. if (!error)
  222. {
  223. std::cout << "Messages sent\n";
  224. }
  225. else
  226. {
  227. std::cout << "Error: " << error.message() << "\n";
  228. }
  229. });
  230. io_context.run();
  231. }
  232. //------------------------------------------------------------------------------
  233. void test_future()
  234. {
  235. boost::asio::io_context io_context;
  236. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  237. tcp::socket socket = acceptor.accept();
  238. // Test our asynchronous operation using the use_future completion token.
  239. // This token causes the operation's initiating function to return a future,
  240. // which may be used to synchronously wait for the result of the operation.
  241. std::future<void> f = async_write_messages(
  242. socket, "Testing future\r\n", 5, boost::asio::use_future);
  243. io_context.run();
  244. try
  245. {
  246. // Get the result of the operation.
  247. f.get();
  248. std::cout << "Messages sent\n";
  249. }
  250. catch (const std::exception& e)
  251. {
  252. std::cout << "Error: " << e.what() << "\n";
  253. }
  254. }
  255. //------------------------------------------------------------------------------
  256. int main()
  257. {
  258. test_callback();
  259. test_future();
  260. }