composed_3.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. //
  2. // composed_3.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. The asynchronous operation
  28. // requirements are met by delegating responsibility to the underlying
  29. // operation.
  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, const char* message) const
  60. {
  61. // The async_write operation has a completion handler signature of:
  62. //
  63. // void(boost::system::error_code error, std::size n)
  64. //
  65. // This differs from our operation's signature in that it is also passed
  66. // the number of bytes transferred as an argument of type std::size_t. We
  67. // will adapt our completion handler to async_write's completion handler
  68. // signature by using std::bind, which drops the additional argument.
  69. //
  70. // However, it is essential to the correctness of our composed operation
  71. // that we preserve the executor of the user-supplied completion handler.
  72. // The std::bind function will not do this for us, so we must do this by
  73. // first obtaining the completion handler's associated executor (defaulting
  74. // to the I/O executor - in this case the executor of the socket - if the
  75. // completion handler does not have its own) ...
  76. auto executor = boost::asio::get_associated_executor(
  77. completion_handler, socket.get_executor());
  78. // ... and then binding this executor to our adapted completion handler
  79. // using the boost::asio::bind_executor function.
  80. boost::asio::async_write(socket,
  81. boost::asio::buffer(message, std::strlen(message)),
  82. boost::asio::bind_executor(executor,
  83. std::bind(std::forward<CompletionHandler>(
  84. completion_handler), std::placeholders::_1)));
  85. }
  86. };
  87. template <typename CompletionToken>
  88. auto async_write_message(tcp::socket& socket,
  89. const char* message, CompletionToken&& token)
  90. // The return type of the initiating function is deduced from the combination
  91. // of CompletionToken type and the completion handler's signature. When the
  92. // completion token is a simple callback, the return type is always void.
  93. // In this example, when the completion token is boost::asio::yield_context
  94. // (used for stackful coroutines) the return type would be also be void, as
  95. // there is no non-error argument to the completion handler. When the
  96. // completion token is boost::asio::use_future it would be std::future<void>.
  97. -> typename boost::asio::async_result<
  98. typename std::decay<CompletionToken>::type,
  99. void(boost::system::error_code)>::return_type
  100. {
  101. // The boost::asio::async_initiate function takes:
  102. //
  103. // - our initiation function object,
  104. // - the completion token,
  105. // - the completion handler signature, and
  106. // - any additional arguments we need to initiate the operation.
  107. //
  108. // It then asks the completion token to create a completion handler (i.e. a
  109. // callback) with the specified signature, and invoke the initiation function
  110. // object with this completion handler as well as the additional arguments.
  111. // The return value of async_initiate is the result of our operation's
  112. // initiating function.
  113. //
  114. // Note that we wrap non-const reference arguments in std::reference_wrapper
  115. // to prevent incorrect decay-copies of these objects.
  116. return boost::asio::async_initiate<
  117. CompletionToken, void(boost::system::error_code)>(
  118. async_write_message_initiation(),
  119. token, std::ref(socket), message);
  120. }
  121. //------------------------------------------------------------------------------
  122. void test_callback()
  123. {
  124. boost::asio::io_context io_context;
  125. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  126. tcp::socket socket = acceptor.accept();
  127. // Test our asynchronous operation using a lambda as a callback.
  128. async_write_message(socket, "Testing callback\r\n",
  129. [](const boost::system::error_code& error)
  130. {
  131. if (!error)
  132. {
  133. std::cout << "Message sent\n";
  134. }
  135. else
  136. {
  137. std::cout << "Error: " << error.message() << "\n";
  138. }
  139. });
  140. io_context.run();
  141. }
  142. //------------------------------------------------------------------------------
  143. void test_future()
  144. {
  145. boost::asio::io_context io_context;
  146. tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
  147. tcp::socket socket = acceptor.accept();
  148. // Test our asynchronous operation using the use_future completion token.
  149. // This token causes the operation's initiating function to return a future,
  150. // which may be used to synchronously wait for the result of the operation.
  151. std::future<void> f = async_write_message(
  152. socket, "Testing future\r\n", boost::asio::use_future);
  153. io_context.run();
  154. // Get the result of the operation.
  155. try
  156. {
  157. // Get the result of the operation.
  158. f.get();
  159. std::cout << "Message sent\n";
  160. }
  161. catch (const std::exception& e)
  162. {
  163. std::cout << "Error: " << e.what() << "\n";
  164. }
  165. }
  166. //------------------------------------------------------------------------------
  167. int main()
  168. {
  169. test_callback();
  170. test_future();
  171. }