composed_4.cpp 7.7 KB

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