composed_7.cpp 7.8 KB

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