]>
Commit | Line | Data |
---|---|---|
92f5a8d4 TL |
1 | // |
2 | // composed_5.cpp | |
3 | // ~~~~~~~~~~~~~~ | |
4 | // | |
f67539c2 | 5 | // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) |
92f5a8d4 TL |
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/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 <functional> | |
16 | #include <iostream> | |
17 | #include <memory> | |
18 | #include <sstream> | |
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 | // This composed operation automatically serialises a message, using its I/O | |
32 | // streams insertion operator, before sending it on the socket. To do this, it | |
33 | // must allocate a buffer for the encoded message and ensure this buffer's | |
34 | // validity until the underlying async_write operation completes. | |
35 | ||
36 | // In addition to determining the mechanism by which an asynchronous operation | |
37 | // delivers its result, a completion token also determines the time when the | |
38 | // operation commences. For example, when the completion token is a simple | |
39 | // callback the operation commences before the initiating function returns. | |
40 | // However, if the completion token's delivery mechanism uses a future, we | |
41 | // might instead want to defer initiation of the operation until the returned | |
42 | // future object is waited upon. | |
43 | // | |
44 | // To enable this, when implementing an asynchronous operation we must package | |
45 | // the initiation step as a function object. | |
46 | struct async_write_message_initiation | |
47 | { | |
48 | // The initiation function object's call operator is passed the concrete | |
49 | // completion handler produced by the completion token. This completion | |
50 | // handler matches the asynchronous operation's completion handler signature, | |
51 | // which in this example is: | |
52 | // | |
53 | // void(boost::system::error_code error) | |
54 | // | |
55 | // The initiation function object also receives any additional arguments | |
56 | // required to start the operation. (Note: We could have instead passed these | |
57 | // arguments as members in the initiaton function object. However, we should | |
58 | // prefer to propagate them as function call arguments as this allows the | |
59 | // completion token to optimise how they are passed. For example, a lazy | |
60 | // future which defers initiation would need to make a decay-copy of the | |
61 | // arguments, but when using a simple callback the arguments can be trivially | |
62 | // forwarded straight through.) | |
63 | template <typename CompletionHandler> | |
64 | void operator()(CompletionHandler&& completion_handler, | |
65 | tcp::socket& socket, std::unique_ptr<std::string> encoded_message) const | |
66 | { | |
67 | // In this example, the composed operation's intermediate completion | |
68 | // handler is implemented as a hand-crafted function object, rather than | |
69 | // using a lambda or std::bind. | |
70 | struct intermediate_completion_handler | |
71 | { | |
72 | // The intermediate completion handler holds a reference to the socket so | |
73 | // that it can obtain the I/O executor (see get_executor below). | |
74 | tcp::socket& socket_; | |
75 | ||
76 | // The allocated buffer for the encoded message. The std::unique_ptr | |
77 | // smart pointer is move-only, and as a consequence our intermediate | |
78 | // completion handler is also move-only. | |
79 | std::unique_ptr<std::string> encoded_message_; | |
80 | ||
81 | // The user-supplied completion handler. | |
82 | typename std::decay<CompletionHandler>::type handler_; | |
83 | ||
84 | // The function call operator matches the completion signature of the | |
85 | // async_write operation. | |
86 | void operator()(const boost::system::error_code& error, std::size_t /*n*/) | |
87 | { | |
88 | // Deallocate the encoded message before calling the user-supplied | |
89 | // completion handler. | |
90 | encoded_message_.reset(); | |
91 | ||
92 | // Call the user-supplied handler with the result of the operation. | |
93 | // The arguments must match the completion signature of our composed | |
94 | // operation. | |
95 | handler_(error); | |
96 | } | |
97 | ||
98 | // It is essential to the correctness of our composed operation that we | |
99 | // preserve the executor of the user-supplied completion handler. With a | |
100 | // hand-crafted function object we can do this by defining a nested type | |
101 | // executor_type and member function get_executor. These obtain the | |
102 | // completion handler's associated executor, and default to the I/O | |
103 | // executor - in this case the executor of the socket - if the completion | |
104 | // handler does not have its own. | |
105 | using executor_type = boost::asio::associated_executor_t< | |
106 | typename std::decay<CompletionHandler>::type, | |
107 | tcp::socket::executor_type>; | |
108 | ||
109 | executor_type get_executor() const noexcept | |
110 | { | |
111 | return boost::asio::get_associated_executor( | |
112 | handler_, socket_.get_executor()); | |
113 | } | |
114 | ||
115 | // Although not necessary for correctness, we may also preserve the | |
116 | // allocator of the user-supplied completion handler. This is achieved by | |
117 | // defining a nested type allocator_type and member function | |
118 | // get_allocator. These obtain the completion handler's associated | |
119 | // allocator, and default to std::allocator<void> if the completion | |
120 | // handler does not have its own. | |
121 | using allocator_type = boost::asio::associated_allocator_t< | |
122 | typename std::decay<CompletionHandler>::type, | |
123 | std::allocator<void>>; | |
124 | ||
125 | allocator_type get_allocator() const noexcept | |
126 | { | |
127 | return boost::asio::get_associated_allocator( | |
128 | handler_, std::allocator<void>{}); | |
129 | } | |
130 | }; | |
131 | ||
132 | // Initiate the underlying async_write operation using our intermediate | |
133 | // completion handler. | |
134 | auto encoded_message_buffer = boost::asio::buffer(*encoded_message); | |
135 | boost::asio::async_write(socket, encoded_message_buffer, | |
136 | intermediate_completion_handler{socket, std::move(encoded_message), | |
137 | std::forward<CompletionHandler>(completion_handler)}); | |
138 | } | |
139 | }; | |
140 | ||
141 | template <typename T, typename CompletionToken> | |
142 | auto async_write_message(tcp::socket& socket, | |
143 | const T& message, CompletionToken&& token) | |
144 | // The return type of the initiating function is deduced from the combination | |
145 | // of CompletionToken type and the completion handler's signature. When the | |
146 | // completion token is a simple callback, the return type is always void. | |
147 | // In this example, when the completion token is boost::asio::yield_context | |
148 | // (used for stackful coroutines) the return type would be also be void, as | |
149 | // there is no non-error argument to the completion handler. When the | |
150 | // completion token is boost::asio::use_future it would be std::future<void>. | |
151 | -> typename boost::asio::async_result< | |
152 | typename std::decay<CompletionToken>::type, | |
153 | void(boost::system::error_code)>::return_type | |
154 | { | |
155 | // Encode the message and copy it into an allocated buffer. The buffer will | |
156 | // be maintained for the lifetime of the asynchronous operation. | |
157 | std::ostringstream os; | |
158 | os << message; | |
159 | std::unique_ptr<std::string> encoded_message(new std::string(os.str())); | |
160 | ||
161 | // The boost::asio::async_initiate function takes: | |
162 | // | |
163 | // - our initiation function object, | |
164 | // - the completion token, | |
165 | // - the completion handler signature, and | |
166 | // - any additional arguments we need to initiate the operation. | |
167 | // | |
168 | // It then asks the completion token to create a completion handler (i.e. a | |
169 | // callback) with the specified signature, and invoke the initiation function | |
170 | // object with this completion handler as well as the additional arguments. | |
171 | // The return value of async_initiate is the result of our operation's | |
172 | // initiating function. | |
173 | // | |
174 | // Note that we wrap non-const reference arguments in std::reference_wrapper | |
175 | // to prevent incorrect decay-copies of these objects. | |
176 | return boost::asio::async_initiate< | |
177 | CompletionToken, void(boost::system::error_code)>( | |
178 | async_write_message_initiation(), token, | |
179 | std::ref(socket), std::move(encoded_message)); | |
180 | } | |
181 | ||
182 | //------------------------------------------------------------------------------ | |
183 | ||
184 | void test_callback() | |
185 | { | |
186 | boost::asio::io_context io_context; | |
187 | ||
188 | tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); | |
189 | tcp::socket socket = acceptor.accept(); | |
190 | ||
191 | // Test our asynchronous operation using a lambda as a callback. | |
192 | async_write_message(socket, 123456, | |
193 | [](const boost::system::error_code& error) | |
194 | { | |
195 | if (!error) | |
196 | { | |
197 | std::cout << "Message sent\n"; | |
198 | } | |
199 | else | |
200 | { | |
201 | std::cout << "Error: " << error.message() << "\n"; | |
202 | } | |
203 | }); | |
204 | ||
205 | io_context.run(); | |
206 | } | |
207 | ||
208 | //------------------------------------------------------------------------------ | |
209 | ||
210 | void test_future() | |
211 | { | |
212 | boost::asio::io_context io_context; | |
213 | ||
214 | tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); | |
215 | tcp::socket socket = acceptor.accept(); | |
216 | ||
217 | // Test our asynchronous operation using the use_future completion token. | |
218 | // This token causes the operation's initiating function to return a future, | |
219 | // which may be used to synchronously wait for the result of the operation. | |
220 | std::future<void> f = async_write_message( | |
221 | socket, 654.321, boost::asio::use_future); | |
222 | ||
223 | io_context.run(); | |
224 | ||
225 | try | |
226 | { | |
227 | // Get the result of the operation. | |
228 | f.get(); | |
229 | std::cout << "Message sent\n"; | |
230 | } | |
231 | catch (const std::exception& e) | |
232 | { | |
233 | std::cout << "Exception: " << e.what() << "\n"; | |
234 | } | |
235 | } | |
236 | ||
237 | //------------------------------------------------------------------------------ | |
238 | ||
239 | int main() | |
240 | { | |
241 | test_callback(); | |
242 | test_future(); | |
243 | } |