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