composed_8.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. //
  2. // composed_8.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/compose.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_compose 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. // using asio's stackless coroutines support to express the flow of control. It
  30. // automatically serialises a message, using its I/O streams insertion
  31. // operator, before sending it N times on the socket. To do this, it must
  32. // allocate a buffer for the encoded message and ensure this buffer's validity
  33. // until all underlying async_write operation complete. A one second delay is
  34. // inserted prior to each write operation, using a steady_timer.
  35. #include <boost/asio/yield.hpp>
  36. // In this example, the composed operation's logic is implemented as a state
  37. // machine within a hand-crafted function object.
  38. struct async_write_messages_implementation
  39. {
  40. // The implementation holds a reference to the socket as it is used for
  41. // multiple async_write operations.
  42. tcp::socket& socket_;
  43. // The allocated buffer for the encoded message. The std::unique_ptr smart
  44. // pointer is move-only, and as a consequence our implementation is also
  45. // move-only.
  46. std::unique_ptr<std::string> encoded_message_;
  47. // The repeat count remaining.
  48. std::size_t repeat_count_;
  49. // A steady timer used for introducing a delay.
  50. std::unique_ptr<boost::asio::steady_timer> delay_timer_;
  51. // The coroutine state.
  52. boost::asio::coroutine coro_;
  53. // The first argument to our function object's call operator is a reference
  54. // to the enclosing intermediate completion handler. This intermediate
  55. // completion handler is provided for us by the boost::asio::async_compose
  56. // function, and takes care of all the details required to implement a
  57. // conforming asynchronous operation. When calling an underlying asynchronous
  58. // operation, we pass it this enclosing intermediate completion handler
  59. // as the completion token.
  60. //
  61. // All arguments after the first must be defaulted to allow the state machine
  62. // to be started, as well as to allow the completion handler to match the
  63. // completion signature of both the async_write and steady_timer::async_wait
  64. // operations.
  65. template <typename Self>
  66. void operator()(Self& self,
  67. const boost::system::error_code& error = boost::system::error_code(),
  68. std::size_t = 0)
  69. {
  70. reenter (coro_)
  71. {
  72. while (repeat_count_ > 0)
  73. {
  74. --repeat_count_;
  75. delay_timer_->expires_after(std::chrono::seconds(1));
  76. yield delay_timer_->async_wait(std::move(self));
  77. if (error)
  78. break;
  79. yield boost::asio::async_write(socket_,
  80. boost::asio::buffer(*encoded_message_), std::move(self));
  81. if (error)
  82. break;
  83. }
  84. // Deallocate the encoded message and delay timer before calling the
  85. // user-supplied completion handler.
  86. encoded_message_.reset();
  87. delay_timer_.reset();
  88. // Call the user-supplied handler with the result of the operation.
  89. self.complete(error);
  90. }
  91. }
  92. };
  93. #include <boost/asio/unyield.hpp>
  94. template <typename T, typename CompletionToken>
  95. auto async_write_messages(tcp::socket& socket,
  96. const T& message, std::size_t repeat_count,
  97. CompletionToken&& token)
  98. // The return type of the initiating function is deduced from the combination
  99. // of CompletionToken type and the completion handler's signature. When the
  100. // completion token is a simple callback, the return type is always void.
  101. // In this example, when the completion token is boost::asio::yield_context
  102. // (used for stackful coroutines) the return type would be also be void, as
  103. // there is no non-error argument to the completion handler. When the
  104. // completion token is boost::asio::use_future it would be std::future<void>.
  105. -> typename boost::asio::async_result<
  106. typename std::decay<CompletionToken>::type,
  107. void(boost::system::error_code)>::return_type
  108. {
  109. // Encode the message and copy it into an allocated buffer. The buffer will
  110. // be maintained for the lifetime of the composed asynchronous operation.
  111. std::ostringstream os;
  112. os << message;
  113. std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
  114. // Create a steady_timer to be used for the delay between messages.
  115. std::unique_ptr<boost::asio::steady_timer> delay_timer(
  116. new boost::asio::steady_timer(socket.get_executor()));
  117. // The boost::asio::async_compose function takes:
  118. //
  119. // - our asynchronous operation implementation,
  120. // - the completion token,
  121. // - the completion handler signature, and
  122. // - any I/O objects (or executors) used by the operation
  123. //
  124. // It then wraps our implementation in an intermediate completion handler
  125. // that meets the requirements of a conforming asynchronous operation. This
  126. // includes tracking outstanding work against the I/O executors associated
  127. // with the operation (in this example, this is the socket's executor).
  128. return boost::asio::async_compose<
  129. CompletionToken, void(boost::system::error_code)>(
  130. async_write_messages_implementation{socket,
  131. std::move(encoded_message), repeat_count,
  132. std::move(delay_timer), boost::asio::coroutine()},
  133. token, socket);
  134. }
  135. //------------------------------------------------------------------------------
  136. void test_callback()
  137. {
  138. boost::asio::io_context io_context;
  139. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  140. tcp::socket socket = acceptor.accept();
  141. // Test our asynchronous operation using a lambda as a callback.
  142. async_write_messages(socket, "Testing callback\r\n", 5,
  143. [](const boost::system::error_code& error)
  144. {
  145. if (!error)
  146. {
  147. std::cout << "Messages sent\n";
  148. }
  149. else
  150. {
  151. std::cout << "Error: " << error.message() << "\n";
  152. }
  153. });
  154. io_context.run();
  155. }
  156. //------------------------------------------------------------------------------
  157. void test_future()
  158. {
  159. boost::asio::io_context io_context;
  160. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  161. tcp::socket socket = acceptor.accept();
  162. // Test our asynchronous operation using the use_future completion token.
  163. // This token causes the operation's initiating function to return a future,
  164. // which may be used to synchronously wait for the result of the operation.
  165. std::future<void> f = async_write_messages(
  166. socket, "Testing future\r\n", 5, boost::asio::use_future);
  167. io_context.run();
  168. try
  169. {
  170. // Get the result of the operation.
  171. f.get();
  172. std::cout << "Messages sent\n";
  173. }
  174. catch (const std::exception& e)
  175. {
  176. std::cout << "Error: " << e.what() << "\n";
  177. }
  178. }
  179. //------------------------------------------------------------------------------
  180. int main()
  181. {
  182. test_callback();
  183. test_future();
  184. }