composed_8.cpp 7.3 KB

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