composed_5.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. //
  2. // composed_5.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/io_context.hpp>
  11. #include <boost/asio/ip/tcp.hpp>
  12. #include <boost/asio/use_future.hpp>
  13. #include <boost/asio/write.hpp>
  14. #include <functional>
  15. #include <iostream>
  16. #include <memory>
  17. #include <sstream>
  18. #include <string>
  19. #include <type_traits>
  20. #include <utility>
  21. using boost::asio::ip::tcp;
  22. // NOTE: This example requires the new boost::asio::async_initiate function. For
  23. // an example that works with the Networking TS style of completion tokens,
  24. // please see an older version of asio.
  25. //------------------------------------------------------------------------------
  26. // This composed operation automatically serialises a message, using its I/O
  27. // streams insertion operator, before sending it on the socket. To do this, it
  28. // must allocate a buffer for the encoded message and ensure this buffer's
  29. // validity until the underlying async_write operation completes.
  30. template <typename T, typename CompletionToken>
  31. auto async_write_message(tcp::socket& socket,
  32. const T& message, CompletionToken&& token)
  33. // The return type of the initiating function is deduced from the combination
  34. // of CompletionToken type and the completion handler's signature. When the
  35. // completion token is a simple callback, the return type is always void.
  36. // In this example, when the completion token is boost::asio::yield_context
  37. // (used for stackful coroutines) the return type would be also be void, as
  38. // there is no non-error argument to the completion handler. When the
  39. // completion token is boost::asio::use_future it would be std::future<void>.
  40. //
  41. // In C++14 we can omit the return type as it is automatically deduced from
  42. // the return type of boost::asio::async_initiate.
  43. {
  44. // In addition to determining the mechanism by which an asynchronous
  45. // operation delivers its result, a completion token also determines the time
  46. // when the operation commences. For example, when the completion token is a
  47. // simple callback the operation commences before the initiating function
  48. // returns. However, if the completion token's delivery mechanism uses a
  49. // future, we might instead want to defer initiation of the operation until
  50. // the returned future object is waited upon.
  51. //
  52. // To enable this, when implementing an asynchronous operation we must
  53. // package the initiation step as a function object. The initiation function
  54. // object's call operator is passed the concrete completion handler produced
  55. // by the completion token. This completion handler matches the asynchronous
  56. // operation's completion handler signature, which in this example is:
  57. //
  58. // void(boost::system::error_code error)
  59. //
  60. // The initiation function object also receives any additional arguments
  61. // required to start the operation. (Note: We could have instead passed these
  62. // arguments in the lambda capture set. However, we should prefer to
  63. // propagate them as function call arguments as this allows the completion
  64. // token to optimise how they are passed. For example, a lazy future which
  65. // defers initiation would need to make a decay-copy of the arguments, but
  66. // when using a simple callback the arguments can be trivially forwarded
  67. // straight through.)
  68. auto initiation = [](auto&& completion_handler,
  69. tcp::socket& socket, std::unique_ptr<std::string> encoded_message)
  70. {
  71. // In this example, the composed operation's intermediate completion
  72. // handler is implemented as a hand-crafted function object, rather than
  73. // using a lambda or std::bind.
  74. struct intermediate_completion_handler
  75. {
  76. // The intermediate completion handler holds a reference to the socket so
  77. // that it can obtain the I/O executor (see get_executor below).
  78. tcp::socket& socket_;
  79. // The allocated buffer for the encoded message. The std::unique_ptr
  80. // smart pointer is move-only, and as a consequence our intermediate
  81. // completion handler is also move-only.
  82. std::unique_ptr<std::string> encoded_message_;
  83. // The user-supplied completion handler.
  84. typename std::decay<decltype(completion_handler)>::type handler_;
  85. // The function call operator matches the completion signature of the
  86. // async_write operation.
  87. void operator()(const boost::system::error_code& error, std::size_t /*n*/)
  88. {
  89. // Deallocate the encoded message before calling the user-supplied
  90. // completion handler.
  91. encoded_message_.reset();
  92. // Call the user-supplied handler with the result of the operation.
  93. // The arguments must match the completion signature of our composed
  94. // operation.
  95. handler_(error);
  96. }
  97. // It is essential to the correctness of our composed operation that we
  98. // preserve the executor of the user-supplied completion handler. With a
  99. // hand-crafted function object we can do this by defining a nested type
  100. // executor_type and member function get_executor. These obtain the
  101. // completion handler's associated executor, and default to the I/O
  102. // executor - in this case the executor of the socket - if the completion
  103. // handler does not have its own.
  104. using executor_type = boost::asio::associated_executor_t<
  105. typename std::decay<decltype(completion_handler)>::type,
  106. tcp::socket::executor_type>;
  107. executor_type get_executor() const noexcept
  108. {
  109. return boost::asio::get_associated_executor(
  110. handler_, socket_.get_executor());
  111. }
  112. // Although not necessary for correctness, we may also preserve the
  113. // allocator of the user-supplied completion handler. This is achieved by
  114. // defining a nested type allocator_type and member function
  115. // get_allocator. These obtain the completion handler's associated
  116. // allocator, and default to std::allocator<void> if the completion
  117. // handler does not have its own.
  118. using allocator_type = boost::asio::associated_allocator_t<
  119. typename std::decay<decltype(completion_handler)>::type,
  120. std::allocator<void>>;
  121. allocator_type get_allocator() const noexcept
  122. {
  123. return boost::asio::get_associated_allocator(
  124. handler_, std::allocator<void>{});
  125. }
  126. };
  127. // Initiate the underlying async_write operation using our intermediate
  128. // completion handler.
  129. auto encoded_message_buffer = boost::asio::buffer(*encoded_message);
  130. boost::asio::async_write(socket, encoded_message_buffer,
  131. intermediate_completion_handler{socket, std::move(encoded_message),
  132. std::forward<decltype(completion_handler)>(completion_handler)});
  133. };
  134. // Encode the message and copy it into an allocated buffer. The buffer will
  135. // be maintained for the lifetime of the asynchronous operation.
  136. std::ostringstream os;
  137. os << message;
  138. std::unique_ptr<std::string> encoded_message(new std::string(os.str()));
  139. // The boost::asio::async_initiate function takes:
  140. //
  141. // - our initiation function object,
  142. // - the completion token,
  143. // - the completion handler signature, and
  144. // - any additional arguments we need to initiate the operation.
  145. //
  146. // It then asks the completion token to create a completion handler (i.e. a
  147. // callback) with the specified signature, and invoke the initiation function
  148. // object with this completion handler as well as the additional arguments.
  149. // The return value of async_initiate is the result of our operation's
  150. // initiating function.
  151. //
  152. // Note that we wrap non-const reference arguments in std::reference_wrapper
  153. // to prevent incorrect decay-copies of these objects.
  154. return boost::asio::async_initiate<
  155. CompletionToken, void(boost::system::error_code)>(
  156. initiation, token, std::ref(socket),
  157. std::move(encoded_message));
  158. }
  159. //------------------------------------------------------------------------------
  160. void test_callback()
  161. {
  162. boost::asio::io_context io_context;
  163. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  164. tcp::socket socket = acceptor.accept();
  165. // Test our asynchronous operation using a lambda as a callback.
  166. async_write_message(socket, 123456,
  167. [](const boost::system::error_code& error)
  168. {
  169. if (!error)
  170. {
  171. std::cout << "Message sent\n";
  172. }
  173. else
  174. {
  175. std::cout << "Error: " << error.message() << "\n";
  176. }
  177. });
  178. io_context.run();
  179. }
  180. //------------------------------------------------------------------------------
  181. void test_future()
  182. {
  183. boost::asio::io_context io_context;
  184. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  185. tcp::socket socket = acceptor.accept();
  186. // Test our asynchronous operation using the use_future completion token.
  187. // This token causes the operation's initiating function to return a future,
  188. // which may be used to synchronously wait for the result of the operation.
  189. std::future<void> f = async_write_message(
  190. socket, 654.321, boost::asio::use_future);
  191. io_context.run();
  192. try
  193. {
  194. // Get the result of the operation.
  195. f.get();
  196. std::cout << "Message sent\n";
  197. }
  198. catch (const std::exception& e)
  199. {
  200. std::cout << "Exception: " << e.what() << "\n";
  201. }
  202. }
  203. //------------------------------------------------------------------------------
  204. int main()
  205. {
  206. test_callback();
  207. test_future();
  208. }