composed_3.cpp 7.3 KB

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