composed_4.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. //
  2. // composed_4.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/bind_executor.hpp>
  11. #include <boost/asio/io_context.hpp>
  12. #include <boost/asio/ip/tcp.hpp>
  13. #include <boost/asio/use_future.hpp>
  14. #include <boost/asio/write.hpp>
  15. #include <cstring>
  16. #include <functional>
  17. #include <iostream>
  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. // In this composed operation we repackage an existing operation, but with a
  27. // different completion handler signature. We will also intercept an empty
  28. // message as an invalid argument, and propagate the corresponding error to the
  29. // user. The asynchronous operation requirements are met by delegating
  30. // responsibility to the underlying operation.
  31. // In addition to determining the mechanism by which an asynchronous operation
  32. // delivers its result, a completion token also determines the time when the
  33. // operation commences. For example, when the completion token is a simple
  34. // callback the operation commences before the initiating function returns.
  35. // However, if the completion token's delivery mechanism uses a future, we
  36. // might instead want to defer initiation of the operation until the returned
  37. // future object is waited upon.
  38. //
  39. // To enable this, when implementing an asynchronous operation we must package
  40. // the initiation step as a function object.
  41. struct async_write_message_initiation
  42. {
  43. // The initiation function object's call operator is passed the concrete
  44. // completion handler produced by the completion token. This completion
  45. // handler matches the asynchronous operation's completion handler signature,
  46. // which in this example is:
  47. //
  48. // void(boost::system::error_code error)
  49. //
  50. // The initiation function object also receives any additional arguments
  51. // required to start the operation. (Note: We could have instead passed these
  52. // arguments as members in the initiaton function object. However, we should
  53. // prefer to propagate them as function call arguments as this allows the
  54. // completion token to optimise how they are passed. For example, a lazy
  55. // future which defers initiation would need to make a decay-copy of the
  56. // arguments, but when using a simple callback the arguments can be trivially
  57. // forwarded straight through.)
  58. template <typename CompletionHandler>
  59. void operator()(CompletionHandler&& completion_handler,
  60. tcp::socket& socket, const char* message) const
  61. {
  62. // The post operation has a completion handler signature of:
  63. //
  64. // void()
  65. //
  66. // and the async_write operation has a completion handler signature of:
  67. //
  68. // void(boost::system::error_code error, std::size n)
  69. //
  70. // Both of these operations' completion handler signatures differ from our
  71. // operation's completion handler signature. We will adapt our completion
  72. // handler to these signatures by using std::bind, which drops the
  73. // additional arguments.
  74. //
  75. // However, it is essential to the correctness of our composed operation
  76. // that we preserve the executor of the user-supplied completion handler.
  77. // The std::bind function will not do this for us, so we must do this by
  78. // first obtaining the completion handler's associated executor (defaulting
  79. // to the I/O executor - in this case the executor of the socket - if the
  80. // completion handler does not have its own) ...
  81. auto executor = boost::asio::get_associated_executor(
  82. completion_handler, socket.get_executor());
  83. // ... and then binding this executor to our adapted completion handler
  84. // using the boost::asio::bind_executor function.
  85. std::size_t length = std::strlen(message);
  86. if (length == 0)
  87. {
  88. boost::asio::post(
  89. boost::asio::bind_executor(executor,
  90. std::bind(std::forward<CompletionHandler>(completion_handler),
  91. boost::asio::error::invalid_argument)));
  92. }
  93. else
  94. {
  95. boost::asio::async_write(socket,
  96. boost::asio::buffer(message, length),
  97. boost::asio::bind_executor(executor,
  98. std::bind(std::forward<CompletionHandler>(completion_handler),
  99. std::placeholders::_1)));
  100. }
  101. }
  102. };
  103. template <typename CompletionToken>
  104. auto async_write_message(tcp::socket& socket,
  105. const char* message, CompletionToken&& token)
  106. // The return type of the initiating function is deduced from the combination
  107. // of CompletionToken type and the completion handler's signature. When the
  108. // completion token is a simple callback, the return type is always void.
  109. // In this example, when the completion token is boost::asio::yield_context
  110. // (used for stackful coroutines) the return type would be also be void, as
  111. // there is no non-error argument to the completion handler. When the
  112. // completion token is boost::asio::use_future it would be std::future<void>.
  113. -> typename boost::asio::async_result<
  114. typename std::decay<CompletionToken>::type,
  115. void(boost::system::error_code)>::return_type
  116. {
  117. // The boost::asio::async_initiate function takes:
  118. //
  119. // - our initiation function object,
  120. // - the completion token,
  121. // - the completion handler signature, and
  122. // - any additional arguments we need to initiate the operation.
  123. //
  124. // It then asks the completion token to create a completion handler (i.e. a
  125. // callback) with the specified signature, and invoke the initiation function
  126. // object with this completion handler as well as the additional arguments.
  127. // The return value of async_initiate is the result of our operation's
  128. // initiating function.
  129. //
  130. // Note that we wrap non-const reference arguments in std::reference_wrapper
  131. // to prevent incorrect decay-copies of these objects.
  132. return boost::asio::async_initiate<
  133. CompletionToken, void(boost::system::error_code)>(
  134. async_write_message_initiation(),
  135. token, std::ref(socket), message);
  136. }
  137. //------------------------------------------------------------------------------
  138. void test_callback()
  139. {
  140. boost::asio::io_context io_context;
  141. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  142. tcp::socket socket = acceptor.accept();
  143. // Test our asynchronous operation using a lambda as a callback.
  144. async_write_message(socket, "",
  145. [](const boost::system::error_code& error)
  146. {
  147. if (!error)
  148. {
  149. std::cout << "Message sent\n";
  150. }
  151. else
  152. {
  153. std::cout << "Error: " << error.message() << "\n";
  154. }
  155. });
  156. io_context.run();
  157. }
  158. //------------------------------------------------------------------------------
  159. void test_future()
  160. {
  161. boost::asio::io_context io_context;
  162. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  163. tcp::socket socket = acceptor.accept();
  164. // Test our asynchronous operation using the use_future completion token.
  165. // This token causes the operation's initiating function to return a future,
  166. // which may be used to synchronously wait for the result of the operation.
  167. std::future<void> f = async_write_message(
  168. socket, "", boost::asio::use_future);
  169. io_context.run();
  170. try
  171. {
  172. // Get the result of the operation.
  173. f.get();
  174. std::cout << "Message sent\n";
  175. }
  176. catch (const std::exception& e)
  177. {
  178. std::cout << "Exception: " << e.what() << "\n";
  179. }
  180. }
  181. //------------------------------------------------------------------------------
  182. int main()
  183. {
  184. test_callback();
  185. test_future();
  186. }