composed_6.cpp 12 KB

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