5 // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
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>
20 #include <type_traits>
23 using boost::asio::ip::tcp
;
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.
29 //------------------------------------------------------------------------------
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.
36 template <typename T
, typename CompletionToken
>
37 auto async_write_message(tcp::socket
& socket
,
38 const T
& 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>.
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.
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.
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:
64 // void(boost::system::error_code error)
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
74 auto initiation
= [](auto&& completion_handler
,
75 tcp::socket
& socket
, std::unique_ptr
<std::string
> encoded_message
)
77 // In this example, the composed operation's intermediate completion
78 // handler is implemented as a hand-crafted function object, rather than
79 // using a lambda or std::bind.
80 struct intermediate_completion_handler
82 // The intermediate completion handler holds a reference to the socket so
83 // that it can obtain the I/O executor (see get_executor below).
86 // The allocated buffer for the encoded message. The std::unique_ptr
87 // smart pointer is move-only, and as a consequence our intermediate
88 // completion handler is also move-only.
89 std::unique_ptr
<std::string
> encoded_message_
;
91 // The user-supplied completion handler.
92 typename
std::decay
<decltype(completion_handler
)>::type handler_
;
94 // The function call operator matches the completion signature of the
95 // async_write operation.
96 void operator()(const boost::system::error_code
& error
, std::size_t /*n*/)
98 // Deallocate the encoded message before calling the user-supplied
99 // completion handler.
100 encoded_message_
.reset();
102 // Call the user-supplied handler with the result of the operation.
103 // The arguments must match the completion signature of our composed
108 // It is essential to the correctness of our composed operation that we
109 // preserve the executor of the user-supplied completion handler. With a
110 // hand-crafted function object we can do this by defining a nested type
111 // executor_type and member function get_executor. These obtain the
112 // completion handler's associated executor, and default to the I/O
113 // executor - in this case the executor of the socket - if the completion
114 // handler does not have its own.
115 using executor_type
= boost::asio::associated_executor_t
<
116 typename
std::decay
<decltype(completion_handler
)>::type
,
117 tcp::socket::executor_type
>;
119 executor_type
get_executor() const noexcept
121 return boost::asio::get_associated_executor(
122 handler_
, socket_
.get_executor());
125 // Although not necessary for correctness, we may also preserve the
126 // allocator of the user-supplied completion handler. This is achieved by
127 // defining a nested type allocator_type and member function
128 // get_allocator. These obtain the completion handler's associated
129 // allocator, and default to std::allocator<void> if the completion
130 // handler does not have its own.
131 using allocator_type
= boost::asio::associated_allocator_t
<
132 typename
std::decay
<decltype(completion_handler
)>::type
,
133 std::allocator
<void>>;
135 allocator_type
get_allocator() const noexcept
137 return boost::asio::get_associated_allocator(
138 handler_
, std::allocator
<void>{});
142 // Initiate the underlying async_write operation using our intermediate
143 // completion handler.
144 auto encoded_message_buffer
= boost::asio::buffer(*encoded_message
);
145 boost::asio::async_write(socket
, encoded_message_buffer
,
146 intermediate_completion_handler
{socket
, std::move(encoded_message
),
147 std::forward
<decltype(completion_handler
)>(completion_handler
)});
150 // Encode the message and copy it into an allocated buffer. The buffer will
151 // be maintained for the lifetime of the asynchronous operation.
152 std::ostringstream os
;
154 std::unique_ptr
<std::string
> encoded_message(new std::string(os
.str()));
156 // The boost::asio::async_initiate function takes:
158 // - our initiation function object,
159 // - the completion token,
160 // - the completion handler signature, and
161 // - any additional arguments we need to initiate the operation.
163 // It then asks the completion token to create a completion handler (i.e. a
164 // callback) with the specified signature, and invoke the initiation function
165 // object with this completion handler as well as the additional arguments.
166 // The return value of async_initiate is the result of our operation's
167 // initiating function.
169 // Note that we wrap non-const reference arguments in std::reference_wrapper
170 // to prevent incorrect decay-copies of these objects.
171 return boost::asio::async_initiate
<
172 CompletionToken
, void(boost::system::error_code
)>(
173 initiation
, token
, std::ref(socket
),
174 std::move(encoded_message
));
177 //------------------------------------------------------------------------------
181 boost::asio::io_context io_context
;
183 tcp::acceptor
acceptor(io_context
, {tcp::v4(), 55555});
184 tcp::socket socket
= acceptor
.accept();
186 // Test our asynchronous operation using a lambda as a callback.
187 async_write_message(socket
, 123456,
188 [](const boost::system::error_code
& error
)
192 std::cout
<< "Message sent\n";
196 std::cout
<< "Error: " << error
.message() << "\n";
203 //------------------------------------------------------------------------------
207 boost::asio::io_context io_context
;
209 tcp::acceptor
acceptor(io_context
, {tcp::v4(), 55555});
210 tcp::socket socket
= acceptor
.accept();
212 // Test our asynchronous operation using the use_future completion token.
213 // This token causes the operation's initiating function to return a future,
214 // which may be used to synchronously wait for the result of the operation.
215 std::future
<void> f
= async_write_message(
216 socket
, 654.321, boost::asio::use_future
);
222 // Get the result of the operation.
224 std::cout
<< "Message sent\n";
226 catch (const std::exception
& e
)
228 std::cout
<< "Exception: " << e
.what() << "\n";
232 //------------------------------------------------------------------------------