composed_7.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. //
  2. // composed_7.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. // 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. // Encode the message and copy it into an allocated buffer. The buffer will
  50. // be maintained for the lifetime of the composed asynchronous operation.
  51. std::ostringstream os;
  52. os << message;
  53. std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
  54. // Create a steady_timer to be used for the delay between messages.
  55. std::unique_ptr<boost::asio::steady_timer> delay_timer(
  56. new boost::asio::steady_timer(socket.get_executor()));
  57. // To manage the cycle between the multiple underlying asychronous
  58. // operations, our implementation is a state machine.
  59. enum { starting, waiting, writing };
  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 state
  68. // machine 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. // To manage the cycle between the multiple underlying asychronous
  99. // operations, our implementation is a state machine.
  100. state = starting
  101. ]
  102. (
  103. auto& self,
  104. const boost::system::error_code& error = {},
  105. std::size_t = 0
  106. ) mutable
  107. {
  108. if (!error)
  109. {
  110. switch (state)
  111. {
  112. case starting:
  113. case writing:
  114. if (repeat_count > 0)
  115. {
  116. --repeat_count;
  117. state = waiting;
  118. delay_timer->expires_after(std::chrono::seconds(1));
  119. delay_timer->async_wait(std::move(self));
  120. return; // Composed operation not yet complete.
  121. }
  122. break; // Composed operation complete, continue below.
  123. case waiting:
  124. state = writing;
  125. boost::asio::async_write(socket,
  126. boost::asio::buffer(*encoded_message), std::move(self));
  127. return; // Composed operation not yet complete.
  128. }
  129. }
  130. // This point is reached only on completion of the entire composed
  131. // operation.
  132. // Deallocate the encoded message and delay timer before calling the
  133. // user-supplied completion handler.
  134. encoded_message.reset();
  135. delay_timer.reset();
  136. // Call the user-supplied handler with the result of the operation.
  137. self.complete(error);
  138. },
  139. token, socket);
  140. }
  141. //------------------------------------------------------------------------------
  142. void test_callback()
  143. {
  144. boost::asio::io_context io_context;
  145. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  146. tcp::socket socket = acceptor.accept();
  147. // Test our asynchronous operation using a lambda as a callback.
  148. async_write_messages(socket, "Testing callback\r\n", 5,
  149. [](const boost::system::error_code& error)
  150. {
  151. if (!error)
  152. {
  153. std::cout << "Messages sent\n";
  154. }
  155. else
  156. {
  157. std::cout << "Error: " << error.message() << "\n";
  158. }
  159. });
  160. io_context.run();
  161. }
  162. //------------------------------------------------------------------------------
  163. void test_future()
  164. {
  165. boost::asio::io_context io_context;
  166. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  167. tcp::socket socket = acceptor.accept();
  168. // Test our asynchronous operation using the use_future completion token.
  169. // This token causes the operation's initiating function to return a future,
  170. // which may be used to synchronously wait for the result of the operation.
  171. std::future<void> f = async_write_messages(
  172. socket, "Testing future\r\n", 5, boost::asio::use_future);
  173. io_context.run();
  174. try
  175. {
  176. // Get the result of the operation.
  177. f.get();
  178. std::cout << "Messages sent\n";
  179. }
  180. catch (const std::exception& e)
  181. {
  182. std::cout << "Error: " << e.what() << "\n";
  183. }
  184. }
  185. //------------------------------------------------------------------------------
  186. int main()
  187. {
  188. test_callback();
  189. test_future();
  190. }