composed_5.cpp 9.5 KB

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