repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
asio
data/projects/asio/example/cpp14/operations/composed_6.cpp
// // composed_6.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/executor_work_guard.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation shows composition of multiple underlying operations. // It automatically serialises a message, using its I/O streams insertion // operator, before sending it N times on the socket. To do this, it must // allocate a buffer for the encoded message and ensure this buffer's validity // until all underlying async_write operation complete. A one second delay is // inserted prior to each write operation, using a steady_timer. template <typename T, typename CompletionToken> auto async_write_messages(tcp::socket& socket, const T& message, std::size_t repeat_count, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++14 we can omit the return type as it is automatically deduced from // the return type of boost::asio::async_initiate. { // In addition to determining the mechanism by which an asynchronous // operation delivers its result, a completion token also determines the time // when the operation commences. For example, when the completion token is a // simple callback the operation commences before the initiating function // returns. However, if the completion token's delivery mechanism uses a // future, we might instead want to defer initiation of the operation until // the returned future object is waited upon. // // To enable this, when implementing an asynchronous operation we must // package the initiation step as a function object. The initiation function // object's call operator is passed the concrete completion handler produced // by the completion token. This completion handler matches the asynchronous // operation's completion handler signature, which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments in the lambda capture set. However, we should prefer to // propagate them as function call arguments as this allows the completion // token to optimise how they are passed. For example, a lazy future which // defers initiation would need to make a decay-copy of the arguments, but // when using a simple callback the arguments can be trivially forwarded // straight through.) auto initiation = [](auto&& completion_handler, tcp::socket& socket, std::unique_ptr<std::string> encoded_message, std::size_t repeat_count, std::unique_ptr<boost::asio::steady_timer> delay_timer) { // In this example, the composed operation's intermediate completion // handler is implemented as a hand-crafted function object. struct intermediate_completion_handler { // The intermediate completion handler holds a reference to the socket as // it is used for multiple async_write operations, as well as for // obtaining the I/O executor (see get_executor below). tcp::socket& socket_; // The allocated buffer for the encoded message. The std::unique_ptr // smart pointer is move-only, and as a consequence our intermediate // completion handler is also move-only. std::unique_ptr<std::string> encoded_message_; // The repeat count remaining. std::size_t repeat_count_; // A steady timer used for introducing a delay. std::unique_ptr<boost::asio::steady_timer> delay_timer_; // To manage the cycle between the multiple underlying asychronous // operations, our intermediate completion handler is implemented as a // state machine. enum { starting, waiting, writing } state_; // As our composed operation performs multiple underlying I/O operations, // we should maintain a work object against the I/O executor. This tells // the I/O executor that there is still more work to come in the future. boost::asio::executor_work_guard<tcp::socket::executor_type> io_work_; // The user-supplied completion handler, called once only on completion // of the entire composed operation. typename std::decay<decltype(completion_handler)>::type handler_; // By having a default value for the second argument, this function call // operator matches the completion signature of both the async_write and // steady_timer::async_wait operations. void operator()(const boost::system::error_code& error, std::size_t = 0) { if (!error) { switch (state_) { case starting: case writing: if (repeat_count_ > 0) { --repeat_count_; state_ = waiting; delay_timer_->expires_after(std::chrono::seconds(1)); delay_timer_->async_wait(std::move(*this)); return; // Composed operation not yet complete. } break; // Composed operation complete, continue below. case waiting: state_ = writing; boost::asio::async_write(socket_, boost::asio::buffer(*encoded_message_), std::move(*this)); return; // Composed operation not yet complete. } } // This point is reached only on completion of the entire composed // operation. // We no longer have any future work coming for the I/O executor. io_work_.reset(); // Deallocate the encoded message before calling the user-supplied // completion handler. encoded_message_.reset(); // Call the user-supplied handler with the result of the operation. handler_(error); } // It is essential to the correctness of our composed operation that we // preserve the executor of the user-supplied completion handler. With a // hand-crafted function object we can do this by defining a nested type // executor_type and member function get_executor. These obtain the // completion handler's associated executor, and default to the I/O // executor - in this case the executor of the socket - if the completion // handler does not have its own. using executor_type = boost::asio::associated_executor_t< typename std::decay<decltype(completion_handler)>::type, tcp::socket::executor_type>; executor_type get_executor() const noexcept { return boost::asio::get_associated_executor( handler_, socket_.get_executor()); } // Although not necessary for correctness, we may also preserve the // allocator of the user-supplied completion handler. This is achieved by // defining a nested type allocator_type and member function // get_allocator. These obtain the completion handler's associated // allocator, and default to std::allocator<void> if the completion // handler does not have its own. using allocator_type = boost::asio::associated_allocator_t< typename std::decay<decltype(completion_handler)>::type, std::allocator<void>>; allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator( handler_, std::allocator<void>{}); } }; // Initiate the underlying async_write operation using our intermediate // completion handler. auto encoded_message_buffer = boost::asio::buffer(*encoded_message); boost::asio::async_write(socket, encoded_message_buffer, intermediate_completion_handler{ socket, std::move(encoded_message), repeat_count, std::move(delay_timer), intermediate_completion_handler::starting, boost::asio::make_work_guard(socket.get_executor()), std::forward<decltype(completion_handler)>(completion_handler)}); }; // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the composed asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // Create a steady_timer to be used for the delay between messages. std::unique_ptr<boost::asio::steady_timer> delay_timer( new boost::asio::steady_timer(socket.get_executor())); // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( initiation, token, std::ref(socket), std::move(encoded_message), repeat_count, std::move(delay_timer)); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_messages(socket, "Testing callback\r\n", 5, [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_messages(socket, "Testing deferred\r\n", 5, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_messages( socket, "Testing future\r\n", 5, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Messages sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/operations/composed_3.cpp
// // composed_3.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/bind_executor.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <cstring> #include <functional> #include <iostream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // In this composed operation we repackage an existing operation, but with a // different completion handler signature. The asynchronous operation // requirements are met by delegating responsibility to the underlying // operation. template <typename CompletionToken> auto async_write_message(tcp::socket& socket, const char* message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++14 we can omit the return type as it is automatically deduced from // the return type of boost::asio::async_initiate. { // In addition to determining the mechanism by which an asynchronous // operation delivers its result, a completion token also determines the time // when the operation commences. For example, when the completion token is a // simple callback the operation commences before the initiating function // returns. However, if the completion token's delivery mechanism uses a // future, we might instead want to defer initiation of the operation until // the returned future object is waited upon. // // To enable this, when implementing an asynchronous operation we must // package the initiation step as a function object. The initiation function // object's call operator is passed the concrete completion handler produced // by the completion token. This completion handler matches the asynchronous // operation's completion handler signature, which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments in the lambda capture set. However, we should prefer to // propagate them as function call arguments as this allows the completion // token to optimise how they are passed. For example, a lazy future which // defers initiation would need to make a decay-copy of the arguments, but // when using a simple callback the arguments can be trivially forwarded // straight through.) auto initiation = [](auto&& completion_handler, tcp::socket& socket, const char* message) { // The async_write operation has a completion handler signature of: // // void(boost::system::error_code error, std::size n) // // This differs from our operation's signature in that it is also passed // the number of bytes transferred as an argument of type std::size_t. We // will adapt our completion handler to async_write's completion handler // signature by using std::bind, which drops the additional argument. // // However, it is essential to the correctness of our composed operation // that we preserve the executor of the user-supplied completion handler. // The std::bind function will not do this for us, so we must do this by // first obtaining the completion handler's associated executor (defaulting // to the I/O executor - in this case the executor of the socket - if the // completion handler does not have its own) ... auto executor = boost::asio::get_associated_executor( completion_handler, socket.get_executor()); // ... and then binding this executor to our adapted completion handler // using the boost::asio::bind_executor function. boost::asio::async_write(socket, boost::asio::buffer(message, std::strlen(message)), boost::asio::bind_executor(executor, std::bind(std::forward<decltype(completion_handler)>( completion_handler), std::placeholders::_1))); }; // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( initiation, token, std::ref(socket), message); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, "Testing callback\r\n", [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, "Testing deferred\r\n", boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_message( socket, "Testing future\r\n", boost::asio::use_future); io_context.run(); // Get the result of the operation. try { // Get the result of the operation. f.get(); std::cout << "Message sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/operations/composed_7.cpp
// // composed_7.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/compose.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_compose function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation shows composition of multiple underlying operations. // It automatically serialises a message, using its I/O streams insertion // operator, before sending it N times on the socket. To do this, it must // allocate a buffer for the encoded message and ensure this buffer's validity // until all underlying async_write operation complete. A one second delay is // inserted prior to each write operation, using a steady_timer. template <typename T, typename CompletionToken> auto async_write_messages(tcp::socket& socket, const T& message, std::size_t repeat_count, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++14 we can omit the return type as it is automatically deduced from // the return type of boost::asio::async_compose. { // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the composed asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // Create a steady_timer to be used for the delay between messages. std::unique_ptr<boost::asio::steady_timer> delay_timer( new boost::asio::steady_timer(socket.get_executor())); // To manage the cycle between the multiple underlying asychronous // operations, our implementation is a state machine. enum { starting, waiting, writing }; // The boost::asio::async_compose function takes: // // - our asynchronous operation implementation, // - the completion token, // - the completion handler signature, and // - any I/O objects (or executors) used by the operation // // It then wraps our implementation, which is implemented here as a state // machine in a lambda, in an intermediate completion handler that meets the // requirements of a conforming asynchronous operation. This includes // tracking outstanding work against the I/O executors associated with the // operation (in this example, this is the socket's executor). // // The first argument to our lambda is a reference to the enclosing // intermediate completion handler. This intermediate completion handler is // provided for us by the boost::asio::async_compose function, and takes care // of all the details required to implement a conforming asynchronous // operation. When calling an underlying asynchronous operation, we pass it // this enclosing intermediate completion handler as the completion token. // // All arguments to our lambda after the first must be defaulted to allow the // state machine to be started, as well as to allow the completion handler to // match the completion signature of both the async_write and // steady_timer::async_wait operations. return boost::asio::async_compose< CompletionToken, void(boost::system::error_code)>( [ // The implementation holds a reference to the socket as it is used for // multiple async_write operations. &socket, // The allocated buffer for the encoded message. The std::unique_ptr // smart pointer is move-only, and as a consequence our lambda // implementation is also move-only. encoded_message = std::move(encoded_message), // The repeat count remaining. repeat_count, // A steady timer used for introducing a delay. delay_timer = std::move(delay_timer), // To manage the cycle between the multiple underlying asychronous // operations, our implementation is a state machine. state = starting ] ( auto& self, const boost::system::error_code& error = {}, std::size_t = 0 ) mutable { if (!error) { switch (state) { case starting: case writing: if (repeat_count > 0) { --repeat_count; state = waiting; delay_timer->expires_after(std::chrono::seconds(1)); delay_timer->async_wait(std::move(self)); return; // Composed operation not yet complete. } break; // Composed operation complete, continue below. case waiting: state = writing; boost::asio::async_write(socket, boost::asio::buffer(*encoded_message), std::move(self)); return; // Composed operation not yet complete. } } // This point is reached only on completion of the entire composed // operation. // Deallocate the encoded message and delay timer before calling the // user-supplied completion handler. encoded_message.reset(); delay_timer.reset(); // Call the user-supplied handler with the result of the operation. self.complete(error); }, token, socket); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_messages(socket, "Testing callback\r\n", 5, [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_messages(socket, "Testing deferred\r\n", 5, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_messages( socket, "Testing future\r\n", 5, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Messages sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/operations/callback_wrapper.cpp
// // callback_wrapper.cpp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> //------------------------------------------------------------------------------ // This is a mock implementation of an API that uses a move-only function object // for exposing a callback. The callback has the signature void(std::string). template <typename Callback> void read_input(const std::string& prompt, Callback cb) { std::thread( [prompt, cb = std::move(cb)]() mutable { std::cout << prompt << ": "; std::cout.flush(); std::string line; std::getline(std::cin, line); std::move(cb)(std::move(line)); }).detach(); } //------------------------------------------------------------------------------ // This is an asynchronous operation that wraps the callback-based API. // The initiating function for the asynchronous operation. template <typename CompletionToken> auto async_read_input(const std::string& prompt, CompletionToken&& token) { // Define a function object that contains the code to launch the asynchronous // operation. This is passed the concrete completion handler, followed by any // additional arguments that were passed through the call to async_initiate. auto init = [](auto handler, const std::string& prompt) { // According to the rules for asynchronous operations, we need to track // outstanding work against the handler's associated executor until the // asynchronous operation is complete. auto work = boost::asio::make_work_guard(handler); // Launch the operation with a callback that will receive the result and // pass it through to the asynchronous operation's completion handler. read_input(prompt, [ handler = std::move(handler), work = std::move(work) ](std::string result) mutable { // Get the handler's associated allocator. If the handler does not // specify an allocator, use the recycling allocator as the default. auto alloc = boost::asio::get_associated_allocator( handler, boost::asio::recycling_allocator<void>()); // Dispatch the completion handler through the handler's associated // executor, using the handler's associated allocator. boost::asio::dispatch(work.get_executor(), boost::asio::bind_allocator(alloc, [ handler = std::move(handler), result = std::string(result) ]() mutable { std::move(handler)(result); })); }); }; // The async_initiate function is used to transform the supplied completion // token to the completion handler. When calling this function we explicitly // specify the completion signature of the operation. We must also return the // result of the call since the completion token may produce a return value, // such as a future. return boost::asio::async_initiate<CompletionToken, void(std::string)>( init, // First, pass the function object that launches the operation, token, // then the completion token that will be transformed to a handler, prompt); // and, finally, any additional arguments to the function object. } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; // Test our asynchronous operation using a lambda as a callback. We will use // an io_context to specify an associated executor. async_read_input("Enter your name", boost::asio::bind_executor(io_context, [](const std::string& result) { std::cout << "Hello " << result << "\n"; })); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_read_input("Enter your name", boost::asio::deferred); // Launch our asynchronous operation using a lambda as a callback. We will use // an io_context to obtain an associated executor. std::move(op)( boost::asio::bind_executor(io_context, [](const std::string& result) { std::cout << "Hello " << result << "\n"; })); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<std::string> f = async_read_input("Enter your name", boost::asio::use_future); std::string result = f.get(); std::cout << "Hello " << result << "\n"; } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/operations/composed_8.cpp
// // composed_8.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/compose.hpp> #include <boost/asio/coroutine.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_compose function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation shows composition of multiple underlying operations, // using asio's stackless coroutines support to express the flow of control. It // automatically serialises a message, using its I/O streams insertion // operator, before sending it N times on the socket. To do this, it must // allocate a buffer for the encoded message and ensure this buffer's validity // until all underlying async_write operation complete. A one second delay is // inserted prior to each write operation, using a steady_timer. #include <boost/asio/yield.hpp> template <typename T, typename CompletionToken> auto async_write_messages(tcp::socket& socket, const T& message, std::size_t repeat_count, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++14 we can omit the return type as it is automatically deduced from // the return type of boost::asio::async_compose. { // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the composed asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // Create a steady_timer to be used for the delay between messages. std::unique_ptr<boost::asio::steady_timer> delay_timer( new boost::asio::steady_timer(socket.get_executor())); // The boost::asio::async_compose function takes: // // - our asynchronous operation implementation, // - the completion token, // - the completion handler signature, and // - any I/O objects (or executors) used by the operation // // It then wraps our implementation, which is implemented here as a stackless // coroutine in a lambda, in an intermediate completion handler that meets the // requirements of a conforming asynchronous operation. This includes // tracking outstanding work against the I/O executors associated with the // operation (in this example, this is the socket's executor). // // The first argument to our lambda is a reference to the enclosing // intermediate completion handler. This intermediate completion handler is // provided for us by the boost::asio::async_compose function, and takes care // of all the details required to implement a conforming asynchronous // operation. When calling an underlying asynchronous operation, we pass it // this enclosing intermediate completion handler as the completion token. // // All arguments to our lambda after the first must be defaulted to allow the // state machine to be started, as well as to allow the completion handler to // match the completion signature of both the async_write and // steady_timer::async_wait operations. return boost::asio::async_compose< CompletionToken, void(boost::system::error_code)>( [ // The implementation holds a reference to the socket as it is used for // multiple async_write operations. &socket, // The allocated buffer for the encoded message. The std::unique_ptr // smart pointer is move-only, and as a consequence our lambda // implementation is also move-only. encoded_message = std::move(encoded_message), // The repeat count remaining. repeat_count, // A steady timer used for introducing a delay. delay_timer = std::move(delay_timer), // The coroutine state. coro = boost::asio::coroutine() ] ( auto& self, const boost::system::error_code& error = {}, std::size_t = 0 ) mutable { reenter (coro) { while (repeat_count > 0) { --repeat_count; delay_timer->expires_after(std::chrono::seconds(1)); yield delay_timer->async_wait(std::move(self)); if (error) break; yield boost::asio::async_write(socket, boost::asio::buffer(*encoded_message), std::move(self)); if (error) break; } // Deallocate the encoded message and delay timer before calling the // user-supplied completion handler. encoded_message.reset(); delay_timer.reset(); // Call the user-supplied handler with the result of the operation. self.complete(error); } }, token, socket); } #include <boost/asio/unyield.hpp> //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_messages(socket, "Testing callback\r\n", 5, [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_messages(socket, "Testing deferred\r\n", 5, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_messages( socket, "Testing future\r\n", 5, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Messages sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/operations/composed_5.cpp
// // composed_5.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation automatically serialises a message, using its I/O // streams insertion operator, before sending it on the socket. To do this, it // must allocate a buffer for the encoded message and ensure this buffer's // validity until the underlying async_write operation completes. template <typename T, typename CompletionToken> auto async_write_message(tcp::socket& socket, const T& message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++14 we can omit the return type as it is automatically deduced from // the return type of boost::asio::async_initiate. { // In addition to determining the mechanism by which an asynchronous // operation delivers its result, a completion token also determines the time // when the operation commences. For example, when the completion token is a // simple callback the operation commences before the initiating function // returns. However, if the completion token's delivery mechanism uses a // future, we might instead want to defer initiation of the operation until // the returned future object is waited upon. // // To enable this, when implementing an asynchronous operation we must // package the initiation step as a function object. The initiation function // object's call operator is passed the concrete completion handler produced // by the completion token. This completion handler matches the asynchronous // operation's completion handler signature, which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments in the lambda capture set. However, we should prefer to // propagate them as function call arguments as this allows the completion // token to optimise how they are passed. For example, a lazy future which // defers initiation would need to make a decay-copy of the arguments, but // when using a simple callback the arguments can be trivially forwarded // straight through.) auto initiation = [](auto&& completion_handler, tcp::socket& socket, std::unique_ptr<std::string> encoded_message) { // In this example, the composed operation's intermediate completion // handler is implemented as a hand-crafted function object, rather than // using a lambda or std::bind. struct intermediate_completion_handler { // The intermediate completion handler holds a reference to the socket so // that it can obtain the I/O executor (see get_executor below). tcp::socket& socket_; // The allocated buffer for the encoded message. The std::unique_ptr // smart pointer is move-only, and as a consequence our intermediate // completion handler is also move-only. std::unique_ptr<std::string> encoded_message_; // The user-supplied completion handler. typename std::decay<decltype(completion_handler)>::type handler_; // The function call operator matches the completion signature of the // async_write operation. void operator()(const boost::system::error_code& error, std::size_t /*n*/) { // Deallocate the encoded message before calling the user-supplied // completion handler. encoded_message_.reset(); // Call the user-supplied handler with the result of the operation. // The arguments must match the completion signature of our composed // operation. handler_(error); } // It is essential to the correctness of our composed operation that we // preserve the executor of the user-supplied completion handler. With a // hand-crafted function object we can do this by defining a nested type // executor_type and member function get_executor. These obtain the // completion handler's associated executor, and default to the I/O // executor - in this case the executor of the socket - if the completion // handler does not have its own. using executor_type = boost::asio::associated_executor_t< typename std::decay<decltype(completion_handler)>::type, tcp::socket::executor_type>; executor_type get_executor() const noexcept { return boost::asio::get_associated_executor( handler_, socket_.get_executor()); } // Although not necessary for correctness, we may also preserve the // allocator of the user-supplied completion handler. This is achieved by // defining a nested type allocator_type and member function // get_allocator. These obtain the completion handler's associated // allocator, and default to std::allocator<void> if the completion // handler does not have its own. using allocator_type = boost::asio::associated_allocator_t< typename std::decay<decltype(completion_handler)>::type, std::allocator<void>>; allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator( handler_, std::allocator<void>{}); } }; // Initiate the underlying async_write operation using our intermediate // completion handler. auto encoded_message_buffer = boost::asio::buffer(*encoded_message); boost::asio::async_write(socket, encoded_message_buffer, intermediate_completion_handler{socket, std::move(encoded_message), std::forward<decltype(completion_handler)>(completion_handler)}); }; // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( initiation, token, std::ref(socket), std::move(encoded_message)); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, 123456, [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, std::string("abcdef"), boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_message( socket, 654.321, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Message sent\n"; } catch (const std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/operations/composed_1.cpp
// // composed_1.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <cstring> #include <iostream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; //------------------------------------------------------------------------------ // This is the simplest example of a composed asynchronous operation, where we // simply repackage an existing operation. The asynchronous operation // requirements are met by delegating responsibility to the underlying // operation. template <typename CompletionToken> auto async_write_message(tcp::socket& socket, const char* message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is void. // However, when the completion token is boost::asio::yield_context (used for // stackful coroutines) the return type would be std::size_t, and when the // completion token is boost::asio::use_future it would be std::future<std::size_t>. // When the completion token is boost::asio::deferred, the return type differs for // each asynchronous operation. // // In C++14 we can omit the return type as it is automatically deduced from // the return type of our underlying asynchronous operation. { // When delegating to the underlying operation we must take care to perfectly // forward the completion token. This ensures that our operation works // correctly with move-only function objects as callbacks, as well as other // completion token types. return boost::asio::async_write(socket, boost::asio::buffer(message, std::strlen(message)), std::forward<CompletionToken>(token)); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, "Testing callback\r\n", [](const boost::system::error_code& error, std::size_t n) { if (!error) { std::cout << n << " bytes transferred\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation with its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, "Testing deferred\r\n", boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error, std::size_t n) { if (!error) { std::cout << n << " bytes transferred\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<std::size_t> f = async_write_message( socket, "Testing future\r\n", boost::asio::use_future); io_context.run(); try { // Get the result of the operation. std::size_t n = f.get(); std::cout << n << " bytes transferred\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp14/parallel_group/wait_for_one_error.cpp
// // wait_for_one_error.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(boost::asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( boost::asio::experimental::wait_for_one_error(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp14/parallel_group/wait_for_one_success.cpp
// // wait_for_one_error.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(boost::asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( boost::asio::experimental::wait_for_one_success(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp14/parallel_group/wait_for_all.cpp
// // wait_for_all.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(boost::asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( boost::asio::experimental::wait_for_all(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp14/parallel_group/wait_for_one.cpp
// // wait_for_one.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(boost::asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( boost::asio::experimental::wait_for_one(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp14/parallel_group/parallel_sort.cpp
// // parallel_sort.cpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/thread/thread.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <random> template < typename Executor, typename RandomAccessIterator, BOOST_ASIO_COMPLETION_TOKEN_FOR(void()) CompletionToken> auto parallel_sort( Executor executor, RandomAccessIterator begin, RandomAccessIterator end, CompletionToken&& token); template < typename Executor, typename RandomAccessIterator> void parallel_sort_impl( Executor executor, RandomAccessIterator begin, RandomAccessIterator end, std::function<void()> continuation) { std::size_t n = end - begin; if (n <= 16384) { boost::asio::post(executor, [=] { std::sort(begin, end); continuation(); } ); } else { boost::asio::experimental::make_parallel_group( [=](auto token) { return parallel_sort(executor, begin, begin + n / 2, token); }, [=](auto token) { return parallel_sort(executor, begin + n / 2, end, token); } ).async_wait( boost::asio::experimental::wait_for_all(), [=](std::array<std::size_t, 2>) { std::inplace_merge(begin, begin + n / 2, end); continuation(); } ); } } template < typename Executor, typename RandomAccessIterator, BOOST_ASIO_COMPLETION_TOKEN_FOR(void()) CompletionToken> auto parallel_sort( Executor executor, RandomAccessIterator begin, RandomAccessIterator end, CompletionToken&& token) { return boost::asio::async_compose<CompletionToken, void()>( [=](auto& self, auto... args) { if (sizeof...(args) == 0) { using self_type = std::decay_t<decltype(self)>; parallel_sort_impl(executor, begin, end, [self = std::make_shared<self_type>(std::move(self))] { boost::asio::dispatch( boost::asio::append( std::move(*self), 0)); } ); } else { self.complete(); } }, token ); } int main() { boost::asio::thread_pool pool(4); std::vector<int> values(100'000'000); std::random_device random_device; std::mt19937 rng(random_device()); std::uniform_int_distribution<int> dist(1, 1'000'000); std::generate(values.begin(), values.end(), [&]{ return dist(rng); }); std::cout << "starting sort\n"; auto begin = std::chrono::high_resolution_clock::now(); parallel_sort( pool.get_executor(), values.begin(), values.end(), boost::asio::use_future ).get(); auto end = std::chrono::high_resolution_clock::now(); auto duration = end - begin; std::cout << "sort took " << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() << " microseconds\n"; }
cpp
asio
data/projects/asio/example/cpp14/parallel_group/ranged_wait_for_all.cpp
// // ranged_wait_for_all.cpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #include <vector> #ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor out(ctx, ::dup(STDOUT_FILENO)); boost::asio::posix::stream_descriptor err(ctx, ::dup(STDERR_FILENO)); using op_type = decltype( out.async_write_some( boost::asio::buffer("", 0), boost::asio::deferred ) ); std::vector<op_type> ops; ops.push_back( out.async_write_some( boost::asio::buffer("first\r\n", 7), boost::asio::deferred ) ); ops.push_back( err.async_write_some( boost::asio::buffer("second\r\n", 8), boost::asio::deferred ) ); boost::asio::experimental::make_parallel_group(ops).async_wait( boost::asio::experimental::wait_for_all(), []( std::vector<std::size_t> completion_order, std::vector<boost::system::error_code> ec, std::vector<std::size_t> n ) { for (std::size_t i = 0; i < completion_order.size(); ++i) { std::size_t idx = completion_order[i]; std::cout << "operation " << idx << " finished: "; std::cout << ec[idx] << ", " << n[idx] << "\n"; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp14/executors/bank_account_1.cpp
#include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <iostream> using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // Traditional active object pattern. // Member functions do not block. class bank_account { int balance_ = 0; mutable static_thread_pool pool_{1}; public: void deposit(int amount) { pool_.executor().execute( [this, amount] { balance_ += amount; }); } void withdraw(int amount) { pool_.executor().execute( [this, amount] { if (balance_ >= amount) balance_ -= amount; }); } void print_balance() const { pool_.executor().execute( [this] { std::cout << "balance = " << balance_ << "\n"; }); } ~bank_account() { pool_.wait(); } }; int main() { bank_account acct; acct.deposit(20); acct.withdraw(10); acct.print_balance(); }
cpp
asio
data/projects/asio/example/cpp14/executors/priority_scheduler.cpp
#include <boost/asio/execution.hpp> #include <condition_variable> #include <iostream> #include <memory> #include <mutex> #include <queue> namespace execution = boost::asio::execution; namespace custom_props { struct priority { template <typename T> static constexpr bool is_applicable_property_v = execution::is_executor<T>::value; static constexpr bool is_requirable = true; static constexpr bool is_preferable = true; using polymorphic_query_result_type = int; int value() const { return value_; } int value_ = 1; }; constexpr priority low_priority{0}; constexpr priority normal_priority{1}; constexpr priority high_priority{2}; } // namespace custom_props class priority_scheduler { public: // A class that satisfies the Executor requirements. class executor_type { public: executor_type(priority_scheduler& ctx) noexcept : context_(ctx), priority_(custom_props::normal_priority.value()) { } priority_scheduler& query(execution::context_t) const noexcept { return context_; } int query(custom_props::priority) const noexcept { return priority_; } executor_type require(custom_props::priority pri) const { executor_type new_ex(*this); new_ex.priority_ = pri.value(); return new_ex; } template <class Func> void execute(Func f) const { auto p(std::make_shared<item<Func>>(priority_, std::move(f))); std::lock_guard<std::mutex> lock(context_.mutex_); context_.queue_.push(p); context_.condition_.notify_one(); } friend bool operator==(const executor_type& a, const executor_type& b) noexcept { return &a.context_ == &b.context_; } friend bool operator!=(const executor_type& a, const executor_type& b) noexcept { return &a.context_ != &b.context_; } private: priority_scheduler& context_; int priority_; }; executor_type executor() noexcept { return executor_type(*const_cast<priority_scheduler*>(this)); } void run() { std::unique_lock<std::mutex> lock(mutex_); for (;;) { condition_.wait(lock, [&]{ return stopped_ || !queue_.empty(); }); if (stopped_) return; auto p(queue_.top()); queue_.pop(); lock.unlock(); p->execute_(p); lock.lock(); } } void stop() { std::lock_guard<std::mutex> lock(mutex_); stopped_ = true; condition_.notify_all(); } private: struct item_base { int priority_; void (*execute_)(std::shared_ptr<item_base>&); }; template <class Func> struct item : item_base { item(int pri, Func f) : function_(std::move(f)) { priority_ = pri; execute_ = [](std::shared_ptr<item_base>& p) { Func tmp(std::move(static_cast<item*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; struct item_comp { bool operator()( const std::shared_ptr<item_base>& a, const std::shared_ptr<item_base>& b) { return a->priority_ < b->priority_; } }; std::mutex mutex_; std::condition_variable condition_; std::priority_queue< std::shared_ptr<item_base>, std::vector<std::shared_ptr<item_base>>, item_comp> queue_; bool stopped_ = false; }; int main() { priority_scheduler sched; auto ex = sched.executor(); auto prefer_low = boost::asio::prefer(ex, custom_props::low_priority); auto low = boost::asio::require(ex, custom_props::low_priority); auto med = boost::asio::require(ex, custom_props::normal_priority); auto high = boost::asio::require(ex, custom_props::high_priority); execution::any_executor<custom_props::priority> poly_high(high); prefer_low.execute([]{ std::cout << "1\n"; }); low.execute([]{ std::cout << "11\n"; }); low.execute([]{ std::cout << "111\n"; }); med.execute([]{ std::cout << "2\n"; }); med.execute([]{ std::cout << "22\n"; }); high.execute([]{ std::cout << "3\n"; }); high.execute([]{ std::cout << "33\n"; }); high.execute([]{ std::cout << "333\n"; }); poly_high.execute([]{ std::cout << "3333\n"; }); boost::asio::require(ex, custom_props::priority{-1}).execute([&]{ sched.stop(); }); sched.run(); std::cout << "polymorphic query result = " << boost::asio::query(poly_high, custom_props::priority{}) << "\n"; }
cpp
asio
data/projects/asio/example/cpp14/executors/async_1.cpp
#include <boost/asio/associated_executor.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <iostream> #include <string> using boost::asio::bind_executor; using boost::asio::get_associated_executor; using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // A function to asynchronously read a single line from an input stream. template <class IoExecutor, class Handler> void async_getline(IoExecutor io_ex, std::istream& is, Handler handler) { // Track work for the handler's associated executor. auto work_ex = boost::asio::prefer( get_associated_executor(handler, io_ex), execution::outstanding_work.tracked); // Post a function object to do the work asynchronously. boost::asio::require(io_ex, execution::blocking.never).execute( [&is, work_ex, handler=std::move(handler)]() mutable { std::string line; std::getline(is, line); // Pass the result to the handler, via the associated executor. boost::asio::prefer(work_ex, execution::blocking.possibly).execute( [line=std::move(line), handler=std::move(handler)]() mutable { handler(std::move(line)); }); }); } int main() { static_thread_pool io_pool(1); static_thread_pool completion_pool(1); std::cout << "Enter a line: "; async_getline(io_pool.executor(), std::cin, bind_executor(completion_pool.executor(), [](std::string line) { std::cout << "Line: " << line << "\n"; })); io_pool.wait(); completion_pool.wait(); }
cpp
asio
data/projects/asio/example/cpp14/executors/fork_join.cpp
#include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <algorithm> #include <condition_variable> #include <memory> #include <mutex> #include <queue> #include <thread> #include <numeric> using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // A fixed-size thread pool used to implement fork/join semantics. Functions // are scheduled using a simple FIFO queue. Implementing work stealing, or // using a queue based on atomic operations, are left as tasks for the reader. class fork_join_pool { public: // The constructor starts a thread pool with the specified number of threads. // Note that the thread_count is not a fixed limit on the pool's concurrency. // Additional threads may temporarily be added to the pool if they join a // fork_executor. explicit fork_join_pool( std::size_t thread_count = std::max(std::thread::hardware_concurrency(), 1u) * 2) : use_count_(1), threads_(thread_count) { try { // Ask each thread in the pool to dequeue and execute functions until // it is time to shut down, i.e. the use count is zero. for (thread_count_ = 0; thread_count_ < thread_count; ++thread_count_) { threads_.executor().execute( [this] { std::unique_lock<std::mutex> lock(mutex_); while (use_count_ > 0) if (!execute_next(lock)) condition_.wait(lock); }); } } catch (...) { stop_threads(); threads_.wait(); throw; } } // The destructor waits for the pool to finish executing functions. ~fork_join_pool() { stop_threads(); threads_.wait(); } private: friend class fork_executor; // The base for all functions that are queued in the pool. struct function_base { std::shared_ptr<std::size_t> work_count_; void (*execute_)(std::shared_ptr<function_base>& p); }; // Execute the next function from the queue, if any. Returns true if a // function was executed, and false if the queue was empty. bool execute_next(std::unique_lock<std::mutex>& lock) { if (queue_.empty()) return false; auto p(queue_.front()); queue_.pop(); lock.unlock(); execute(lock, p); return true; } // Execute a function and decrement the outstanding work. void execute(std::unique_lock<std::mutex>& lock, std::shared_ptr<function_base>& p) { std::shared_ptr<std::size_t> work_count(std::move(p->work_count_)); try { p->execute_(p); lock.lock(); do_work_finished(work_count); } catch (...) { lock.lock(); do_work_finished(work_count); throw; } } // Increment outstanding work. void do_work_started(const std::shared_ptr<std::size_t>& work_count) noexcept { if (++(*work_count) == 1) ++use_count_; } // Decrement outstanding work. Notify waiting threads if we run out. void do_work_finished(const std::shared_ptr<std::size_t>& work_count) noexcept { if (--(*work_count) == 0) { --use_count_; condition_.notify_all(); } } // Dispatch a function, executing it immediately if the queue is already // loaded. Otherwise adds the function to the queue and wakes a thread. void do_execute(std::shared_ptr<function_base> p, const std::shared_ptr<std::size_t>& work_count) { std::unique_lock<std::mutex> lock(mutex_); if (queue_.size() > thread_count_ * 16) { do_work_started(work_count); lock.unlock(); execute(lock, p); } else { queue_.push(p); do_work_started(work_count); condition_.notify_one(); } } // Ask all threads to shut down. void stop_threads() { std::lock_guard<std::mutex> lock(mutex_); --use_count_; condition_.notify_all(); } std::mutex mutex_; std::condition_variable condition_; std::queue<std::shared_ptr<function_base>> queue_; std::size_t use_count_; std::size_t thread_count_; static_thread_pool threads_; }; // A class that satisfies the Executor requirements. Every function or piece of // work associated with a fork_executor is part of a single, joinable group. class fork_executor { public: fork_executor(fork_join_pool& ctx) : context_(ctx), work_count_(std::make_shared<std::size_t>(0)) { } fork_join_pool& query(execution::context_t) const noexcept { return context_; } template <class Func> void execute(Func f) const { auto p(std::make_shared<function<Func>>(std::move(f), work_count_)); context_.do_execute(p, work_count_); } friend bool operator==(const fork_executor& a, const fork_executor& b) noexcept { return a.work_count_ == b.work_count_; } friend bool operator!=(const fork_executor& a, const fork_executor& b) noexcept { return a.work_count_ != b.work_count_; } // Block until all work associated with the executor is complete. While it is // waiting, the thread may be borrowed to execute functions from the queue. void join() const { std::unique_lock<std::mutex> lock(context_.mutex_); while (*work_count_ > 0) if (!context_.execute_next(lock)) context_.condition_.wait(lock); } private: template <class Func> struct function : fork_join_pool::function_base { explicit function(Func f, const std::shared_ptr<std::size_t>& w) : function_(std::move(f)) { work_count_ = w; execute_ = [](std::shared_ptr<fork_join_pool::function_base>& p) { Func tmp(std::move(static_cast<function*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; fork_join_pool& context_; std::shared_ptr<std::size_t> work_count_; }; // Helper class to automatically join a fork_executor when exiting a scope. class join_guard { public: explicit join_guard(const fork_executor& ex) : ex_(ex) {} join_guard(const join_guard&) = delete; join_guard(join_guard&&) = delete; ~join_guard() { ex_.join(); } private: fork_executor ex_; }; //------------------------------------------------------------------------------ #include <algorithm> #include <iostream> #include <random> #include <vector> fork_join_pool pool; template <class Iterator> void fork_join_sort(Iterator begin, Iterator end) { std::size_t n = end - begin; if (n > 32768) { { fork_executor fork(pool); join_guard join(fork); fork.execute([=]{ fork_join_sort(begin, begin + n / 2); }); fork.execute([=]{ fork_join_sort(begin + n / 2, end); }); } std::inplace_merge(begin, begin + n / 2, end); } else { std::sort(begin, end); } } int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: fork_join <size>\n"; return 1; } std::vector<double> vec(std::atoll(argv[1])); std::iota(vec.begin(), vec.end(), 0); std::random_device rd; std::mt19937 g(rd()); std::shuffle(vec.begin(), vec.end(), g); std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); fork_join_sort(vec.begin(), vec.end()); std::chrono::steady_clock::duration elapsed = std::chrono::steady_clock::now() - start; std::cout << "sort took "; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); std::cout << " microseconds" << std::endl; }
cpp
asio
data/projects/asio/example/cpp14/executors/pipeline.cpp
#include <boost/asio/associated_executor.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/execution.hpp> #include <condition_variable> #include <future> #include <memory> #include <mutex> #include <queue> #include <thread> #include <vector> #include <cctype> using boost::asio::executor_binder; using boost::asio::get_associated_executor; namespace execution = boost::asio::execution; // An executor that launches a new thread for each function submitted to it. // This class satisfies the executor requirements. class thread_executor { private: // Singleton execution context that manages threads launched by the new_thread_executor. class thread_bag { friend class thread_executor; void add_thread(std::thread&& t) { std::unique_lock<std::mutex> lock(mutex_); threads_.push_back(std::move(t)); } thread_bag() = default; ~thread_bag() { for (auto& t : threads_) t.join(); } std::mutex mutex_; std::vector<std::thread> threads_; }; public: static thread_bag& query(execution::context_t) { static thread_bag threads; return threads; } static constexpr auto query(execution::blocking_t) { return execution::blocking.never; } template <class Func> void execute(Func f) const { thread_bag& bag = query(execution::context); bag.add_thread(std::thread(std::move(f))); } friend bool operator==(const thread_executor&, const thread_executor&) noexcept { return true; } friend bool operator!=(const thread_executor&, const thread_executor&) noexcept { return false; } }; // Base class for all thread-safe queue implementations. class queue_impl_base { template <class> friend class queue_front; template <class> friend class queue_back; std::mutex mutex_; std::condition_variable condition_; bool stop_ = false; }; // Underlying implementation of a thread-safe queue, shared between the // queue_front and queue_back classes. template <class T> class queue_impl : public queue_impl_base { template <class> friend class queue_front; template <class> friend class queue_back; std::queue<T> queue_; }; // The front end of a queue between consecutive pipeline stages. template <class T> class queue_front { public: typedef T value_type; explicit queue_front(std::shared_ptr<queue_impl<T>> impl) : impl_(impl) { } void push(T t) { std::unique_lock<std::mutex> lock(impl_->mutex_); impl_->queue_.push(std::move(t)); impl_->condition_.notify_one(); } void stop() { std::unique_lock<std::mutex> lock(impl_->mutex_); impl_->stop_ = true; impl_->condition_.notify_one(); } private: std::shared_ptr<queue_impl<T>> impl_; }; // The back end of a queue between consecutive pipeline stages. template <class T> class queue_back { public: typedef T value_type; explicit queue_back(std::shared_ptr<queue_impl<T>> impl) : impl_(impl) { } bool pop(T& t) { std::unique_lock<std::mutex> lock(impl_->mutex_); while (impl_->queue_.empty() && !impl_->stop_) impl_->condition_.wait(lock); if (!impl_->queue_.empty()) { t = impl_->queue_.front(); impl_->queue_.pop(); return true; } return false; } private: std::shared_ptr<queue_impl<T>> impl_; }; // Launch the last stage in a pipeline. template <class T, class F> std::future<void> pipeline(queue_back<T> in, F f) { // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function, and as we're the last stage return a future so that the // caller can wait for the pipeline to finish. std::packaged_task<void()> task( [in, f = std::move(f)]() mutable { f(in); }); std::future<void> fut = task.get_future(); boost::asio::require(ex, execution::blocking.never).execute(std::move(task)); return fut; } // Launch an intermediate stage in a pipeline. template <class T, class F, class... Tail> std::future<void> pipeline(queue_back<T> in, F f, Tail... t) { // Determine the output queue type. typedef typename executor_binder<F, thread_executor>::second_argument_type::value_type output_value_type; // Create the output queue and its implementation. auto out_impl = std::make_shared<queue_impl<output_value_type>>(); queue_front<output_value_type> out(out_impl); queue_back<output_value_type> next_in(out_impl); // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function. boost::asio::require(ex, execution::blocking.never).execute( [in, out, f = std::move(f)]() mutable { f(in, out); out.stop(); }); // Launch the rest of the pipeline. return pipeline(next_in, std::move(t)...); } // Launch the first stage in a pipeline. template <class F, class... Tail> std::future<void> pipeline(F f, Tail... t) { // Determine the output queue type. typedef typename executor_binder<F, thread_executor>::argument_type::value_type output_value_type; // Create the output queue and its implementation. auto out_impl = std::make_shared<queue_impl<output_value_type>>(); queue_front<output_value_type> out(out_impl); queue_back<output_value_type> next_in(out_impl); // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function. boost::asio::require(ex, execution::blocking.never).execute( [out, f = std::move(f)]() mutable { f(out); out.stop(); }); // Launch the rest of the pipeline. return pipeline(next_in, std::move(t)...); } //------------------------------------------------------------------------------ #include <boost/asio/static_thread_pool.hpp> #include <iostream> #include <string> using boost::asio::bind_executor; using boost::asio::static_thread_pool; void reader(queue_front<std::string> out) { std::string line; while (std::getline(std::cin, line)) out.push(line); } void filter(queue_back<std::string> in, queue_front<std::string> out) { std::string line; while (in.pop(line)) if (line.length() > 5) out.push(line); } void upper(queue_back<std::string> in, queue_front<std::string> out) { std::string line; while (in.pop(line)) { std::string new_line; for (char c : line) new_line.push_back(std::toupper(c)); out.push(new_line); } } void writer(queue_back<std::string> in) { std::size_t count = 0; std::string line; while (in.pop(line)) std::cout << count++ << ": " << line << std::endl; } int main() { static_thread_pool pool(1); auto f = pipeline(reader, filter, bind_executor(pool.executor(), upper), writer); f.wait(); }
cpp
asio
data/projects/asio/example/cpp14/executors/actor.cpp
#include <boost/asio/any_io_executor.hpp> #include <boost/asio/defer.hpp> #include <boost/asio/post.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/system_executor.hpp> #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <typeinfo> #include <vector> using boost::asio::any_io_executor; using boost::asio::defer; using boost::asio::post; using boost::asio::strand; using boost::asio::system_executor; //------------------------------------------------------------------------------ // A tiny actor framework // ~~~~~~~~~~~~~~~~~~~~~~ class actor; // Used to identify the sender and recipient of messages. typedef actor* actor_address; // Base class for all registered message handlers. class message_handler_base { public: virtual ~message_handler_base() {} // Used to determine which message handlers receive an incoming message. virtual const std::type_info& message_id() const = 0; }; // Base class for a handler for a specific message type. template <class Message> class message_handler : public message_handler_base { public: // Handle an incoming message. virtual void handle_message(Message msg, actor_address from) = 0; }; // Concrete message handler for a specific message type. template <class Actor, class Message> class mf_message_handler : public message_handler<Message> { public: // Construct a message handler to invoke the specified member function. mf_message_handler(void (Actor::* mf)(Message, actor_address), Actor* a) : function_(mf), actor_(a) { } // Used to determine which message handlers receive an incoming message. virtual const std::type_info& message_id() const { return typeid(Message); } // Handle an incoming message. virtual void handle_message(Message msg, actor_address from) { (actor_->*function_)(std::move(msg), from); } // Determine whether the message handler represents the specified function. bool is_function(void (Actor::* mf)(Message, actor_address)) const { return mf == function_; } private: void (Actor::* function_)(Message, actor_address); Actor* actor_; }; // Base class for all actors. class actor { public: virtual ~actor() { } // Obtain the actor's address for use as a message sender or recipient. actor_address address() { return this; } // Send a message from one actor to another. template <class Message> friend void send(Message msg, actor_address from, actor_address to) { // Execute the message handler in the context of the target's executor. post(to->executor_, [=, msg=std::move(msg)]() mutable { to->call_handler(std::move(msg), from); }); } protected: // Construct the actor to use the specified executor for all message handlers. actor(any_io_executor e) : executor_(std::move(e)) { } // Register a handler for a specific message type. Duplicates are permitted. template <class Actor, class Message> void register_handler(void (Actor::* mf)(Message, actor_address)) { handlers_.push_back( std::make_shared<mf_message_handler<Actor, Message>>( mf, static_cast<Actor*>(this))); } // Deregister a handler. Removes only the first matching handler. template <class Actor, class Message> void deregister_handler(void (Actor::* mf)(Message, actor_address)) { const std::type_info& id = typeid(Message); for (auto iter = handlers_.begin(); iter != handlers_.end(); ++iter) { if ((*iter)->message_id() == id) { auto mh = static_cast<mf_message_handler<Actor, Message>*>(iter->get()); if (mh->is_function(mf)) { handlers_.erase(iter); return; } } } } // Send a message from within a message handler. template <class Message> void tail_send(Message msg, actor_address to) { // Execute the message handler in the context of the target's executor. defer(to->executor_, [=, msg=std::move(msg), from=this] { to->call_handler(std::move(msg), from); }); } private: // Find the matching message handlers, if any, and call them. template <class Message> void call_handler(Message msg, actor_address from) { const std::type_info& message_id = typeid(Message); for (auto& h: handlers_) { if (h->message_id() == message_id) { auto mh = static_cast<message_handler<Message>*>(h.get()); mh->handle_message(msg, from); } } } // All messages associated with a single actor object should be processed // non-concurrently. We use a strand to ensure non-concurrent execution even // if the underlying executor may use multiple threads. strand<any_io_executor> executor_; std::vector<std::shared_ptr<message_handler_base>> handlers_; }; // A concrete actor that allows synchronous message retrieval. template <class Message> class receiver : public actor { public: receiver() : actor(system_executor()) { register_handler(&receiver::message_handler); } // Block until a message has been received. Message wait() { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [this]{ return !message_queue_.empty(); }); Message msg(std::move(message_queue_.front())); message_queue_.pop_front(); return msg; } private: // Handle a new message by adding it to the queue and waking a waiter. void message_handler(Message msg, actor_address /* from */) { std::lock_guard<std::mutex> lock(mutex_); message_queue_.push_back(std::move(msg)); condition_.notify_one(); } std::mutex mutex_; std::condition_variable condition_; std::deque<Message> message_queue_; }; //------------------------------------------------------------------------------ #include <boost/asio/thread_pool.hpp> #include <iostream> using boost::asio::thread_pool; class member : public actor { public: explicit member(any_io_executor e) : actor(std::move(e)) { register_handler(&member::init_handler); } private: void init_handler(actor_address next, actor_address from) { next_ = next; caller_ = from; register_handler(&member::token_handler); deregister_handler(&member::init_handler); } void token_handler(int token, actor_address /*from*/) { int msg(token); actor_address to(caller_); if (token > 0) { msg = token - 1; to = next_; } tail_send(msg, to); } actor_address next_; actor_address caller_; }; int main() { const std::size_t num_threads = 16; const int num_hops = 50000000; const std::size_t num_actors = 503; const int token_value = (num_hops + num_actors - 1) / num_actors; const std::size_t actors_per_thread = num_actors / num_threads; struct single_thread_pool : thread_pool { single_thread_pool() : thread_pool(1) {} }; single_thread_pool pools[num_threads]; std::vector<std::shared_ptr<member>> members(num_actors); receiver<int> rcvr; // Create the member actors. for (std::size_t i = 0; i < num_actors; ++i) members[i] = std::make_shared<member>(pools[(i / actors_per_thread) % num_threads].get_executor()); // Initialise the actors by passing each one the address of the next actor in the ring. for (std::size_t i = num_actors, next_i = 0; i > 0; next_i = --i) send(members[next_i]->address(), rcvr.address(), members[i - 1]->address()); // Send exactly one token to each actor, all with the same initial value, rounding up if required. for (std::size_t i = 0; i < num_actors; ++i) send(token_value, rcvr.address(), members[i]->address()); // Wait for all signal messages, indicating the tokens have all reached zero. for (std::size_t i = 0; i < num_actors; ++i) rcvr.wait(); }
cpp
asio
data/projects/asio/example/cpp14/executors/async_2.cpp
#include <boost/asio/associated_executor.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <iostream> #include <string> using boost::asio::bind_executor; using boost::asio::get_associated_executor; using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // A function to asynchronously read a single line from an input stream. template <class IoExecutor, class Handler> void async_getline(IoExecutor io_ex, std::istream& is, Handler handler) { // Track work for the handler's associated executor. auto work_ex = boost::asio::prefer( get_associated_executor(handler, io_ex), execution::outstanding_work.tracked); // Post a function object to do the work asynchronously. boost::asio::require(io_ex, execution::blocking.never).execute( [&is, work_ex, handler=std::move(handler)]() mutable { std::string line; std::getline(is, line); // Pass the result to the handler, via the associated executor. boost::asio::prefer(work_ex, execution::blocking.possibly).execute( [line=std::move(line), handler=std::move(handler)]() mutable { handler(std::move(line)); }); }); } // A function to asynchronously read multiple lines from an input stream. template <class IoExecutor, class Handler> void async_getlines(IoExecutor io_ex, std::istream& is, std::string init, Handler handler) { // Track work for the I/O executor. auto io_work_ex = boost::asio::prefer(io_ex, execution::outstanding_work.tracked); // Track work for the handler's associated executor. auto handler_work_ex = boost::asio::prefer( get_associated_executor(handler, io_ex), execution::outstanding_work.tracked); // Use the associated executor for each operation in the composition. async_getline(io_work_ex, is, bind_executor(handler_work_ex, [io_work_ex, &is, lines=std::move(init), handler=std::move(handler)] (std::string line) mutable { if (line.empty()) handler(lines); else async_getlines(io_work_ex, is, lines + line + "\n", std::move(handler)); })); } int main() { static_thread_pool io_pool(1); static_thread_pool completion_pool(1); std::cout << "Enter text, terminating with a blank line:\n"; async_getlines(io_pool.executor(), std::cin, "", bind_executor(completion_pool.executor(), [](std::string lines) { std::cout << "Lines:\n" << lines << "\n"; })); io_pool.wait(); completion_pool.wait(); }
cpp
asio
data/projects/asio/example/cpp14/executors/bank_account_2.cpp
#include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <iostream> using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // Traditional active object pattern. // Member functions block until operation is finished. class bank_account { int balance_ = 0; mutable static_thread_pool pool_{1}; public: void deposit(int amount) { boost::asio::require(pool_.executor(), execution::blocking.always).execute( [this, amount] { balance_ += amount; }); } void withdraw(int amount) { boost::asio::require(pool_.executor(), execution::blocking.always).execute( [this, amount] { if (balance_ >= amount) balance_ -= amount; }); } int balance() const { int result = 0; boost::asio::require(pool_.executor(), execution::blocking.always).execute( [this, &result] { result = balance_; }); return result; } }; int main() { bank_account acct; acct.deposit(20); acct.withdraw(10); std::cout << "balance = " << acct.balance() << "\n"; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_7.cpp
// // deferred_7.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::append; using boost::asio::deferred; template <typename CompletionToken> auto async_wait_twice(boost::asio::steady_timer& timer, CompletionToken&& token) { return deferred.values(&timer) | deferred( [](boost::asio::steady_timer* timer) { timer->expires_after(std::chrono::seconds(1)); return timer->async_wait(append(deferred, timer)); } ) | deferred( [](boost::system::error_code ec, boost::asio::steady_timer* timer) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer->expires_after(std::chrono::seconds(1)); return deferred.when(!ec) .then(timer->async_wait(deferred)) .otherwise(deferred.values(ec)); } ) | deferred( [](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.when(!ec) .then(deferred.values(42)) .otherwise(deferred.values(0)); } ) | std::forward<CompletionToken>(token); } int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); // Uncomment the following line to trigger an error in async_wait_twice. //timer.cancel(); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_3.cpp
// // deferred_3.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; template <typename CompletionToken> auto async_wait_twice(boost::asio::steady_timer& timer, CompletionToken&& token) { return timer.async_wait( deferred( [&](boost::system::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) )( std::forward<CompletionToken>(token) ); } int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_6.cpp
// // deferred_6.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::append; using boost::asio::deferred; template <typename CompletionToken> auto async_wait_twice(boost::asio::steady_timer& timer, CompletionToken&& token) { return deferred.values(&timer)( deferred( [](boost::asio::steady_timer* timer) { timer->expires_after(std::chrono::seconds(1)); return timer->async_wait(append(deferred, timer)); } ) )( deferred( [](boost::system::error_code ec, boost::asio::steady_timer* timer) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer->expires_after(std::chrono::seconds(1)); return deferred.when(!ec) .then(timer->async_wait(deferred)) .otherwise(deferred.values(ec)); } ) )( deferred( [](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.when(!ec) .then(deferred.values(42)) .otherwise(deferred.values(0)); } ) )( std::forward<CompletionToken>(token) ); } int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); // Uncomment the following line to trigger an error in async_wait_twice. //timer.cancel(); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_5.cpp
// // deferred_5.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; template <typename CompletionToken> auto async_wait_twice(boost::asio::steady_timer& timer, CompletionToken&& token) { return timer.async_wait( deferred( [&](boost::system::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return deferred.when(!ec) .then(timer.async_wait(deferred)) .otherwise(deferred.values(ec)); } ) )( deferred( [&](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.when(!ec) .then(deferred.values(42)) .otherwise(deferred.values(0)); } ) )( std::forward<CompletionToken>(token) ); } int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); // Uncomment the following line to trigger an error in async_wait_twice. //timer.cancel(); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_2.cpp
// // deferred_2.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); auto deferred_op = timer.async_wait( deferred( [&](boost::system::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) ); std::move(deferred_op)( [](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_1.cpp
// // deferred_1.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); auto deferred_op = timer.async_wait(deferred); std::move(deferred_op)( [](boost::system::error_code ec) { std::cout << "timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/deferred/deferred_4.cpp
// // deferred_4.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; template <typename CompletionToken> auto async_wait_twice(boost::asio::steady_timer& timer, CompletionToken&& token) { return timer.async_wait( deferred( [&](boost::system::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) )( deferred( [&](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.values(42); } ) )( std::forward<CompletionToken>(token) ); } int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp14/iostreams/http_client.cpp
// // http_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio/ts/internet.hpp> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cout << "Usage: http_client <server> <path>\n"; std::cout << "Example:\n"; std::cout << " http_client www.boost.org /LICENSE_1_0.txt\n"; return 1; } boost::asio::ip::tcp::iostream s; // The entire sequence of I/O operations must complete within 60 seconds. // If an expiry occurs, the socket is automatically closed and the stream // becomes bad. s.expires_after(std::chrono::seconds(60)); // Establish a connection to the server. s.connect(argv[1], "http"); if (!s) { std::cout << "Unable to connect: " << s.error().message() << "\n"; return 1; } // Send the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. s << "GET " << argv[2] << " HTTP/1.0\r\n"; s << "Host: " << argv[1] << "\r\n"; s << "Accept: */*\r\n"; s << "Connection: close\r\n\r\n"; // By default, the stream is tied with itself. This means that the stream // automatically flush the buffered output before attempting a read. It is // not necessary not explicitly flush the stream at this point. // Check that response is OK. std::string http_version; s >> http_version; unsigned int status_code; s >> status_code; std::string status_message; std::getline(s, status_message); if (!s || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Process the response headers, which are terminated by a blank line. std::string header; while (std::getline(s, header) && header != "\r") std::cout << header << "\n"; std::cout << "\n"; // Write the remaining data to output. std::cout << s.rdbuf(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/chat_server.cpp
// // chat_server.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <deque> #include <iostream> #include <list> #include <memory> #include <set> #include <string> #include <utility> #include <boost/asio/awaitable.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/co_spawn.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/read_until.hpp> #include <boost/asio/redirect_error.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_awaitable.hpp> #include <boost/asio/write.hpp> using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::redirect_error; using boost::asio::use_awaitable; //---------------------------------------------------------------------- class chat_participant { public: virtual ~chat_participant() {} virtual void deliver(const std::string& msg) = 0; }; typedef std::shared_ptr<chat_participant> chat_participant_ptr; //---------------------------------------------------------------------- class chat_room { public: void join(chat_participant_ptr participant) { participants_.insert(participant); for (auto msg: recent_msgs_) participant->deliver(msg); } void leave(chat_participant_ptr participant) { participants_.erase(participant); } void deliver(const std::string& msg) { recent_msgs_.push_back(msg); while (recent_msgs_.size() > max_recent_msgs) recent_msgs_.pop_front(); for (auto participant: participants_) participant->deliver(msg); } private: std::set<chat_participant_ptr> participants_; enum { max_recent_msgs = 100 }; std::deque<std::string> recent_msgs_; }; //---------------------------------------------------------------------- class chat_session : public chat_participant, public std::enable_shared_from_this<chat_session> { public: chat_session(tcp::socket socket, chat_room& room) : socket_(std::move(socket)), timer_(socket_.get_executor()), room_(room) { timer_.expires_at(std::chrono::steady_clock::time_point::max()); } void start() { room_.join(shared_from_this()); co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->reader(); }, detached); co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->writer(); }, detached); } void deliver(const std::string& msg) { write_msgs_.push_back(msg); timer_.cancel_one(); } private: awaitable<void> reader() { try { for (std::string read_msg;;) { std::size_t n = co_await boost::asio::async_read_until(socket_, boost::asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable); room_.deliver(read_msg.substr(0, n)); read_msg.erase(0, n); } } catch (std::exception&) { stop(); } } awaitable<void> writer() { try { while (socket_.is_open()) { if (write_msgs_.empty()) { boost::system::error_code ec; co_await timer_.async_wait(redirect_error(use_awaitable, ec)); } else { co_await boost::asio::async_write(socket_, boost::asio::buffer(write_msgs_.front()), use_awaitable); write_msgs_.pop_front(); } } } catch (std::exception&) { stop(); } } void stop() { room_.leave(shared_from_this()); socket_.close(); timer_.cancel(); } tcp::socket socket_; boost::asio::steady_timer timer_; chat_room& room_; std::deque<std::string> write_msgs_; }; //---------------------------------------------------------------------- awaitable<void> listener(tcp::acceptor acceptor) { chat_room room; for (;;) { std::make_shared<chat_session>( co_await acceptor.async_accept(use_awaitable), room )->start(); } } //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc < 2) { std::cerr << "Usage: chat_server <port> [<port> ...]\n"; return 1; } boost::asio::io_context io_context(1); for (int i = 1; i < argc; ++i) { unsigned short port = std::atoi(argv[i]); co_spawn(io_context, listener(tcp::acceptor(io_context, {tcp::v4(), port})), detached); } boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/range_based_for.cpp
// // range_based_for.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdio> using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::use_awaitable; class connection_iter { friend class connections; tcp::acceptor* acceptor_ = nullptr; tcp::socket socket_; connection_iter(tcp::acceptor& a, tcp::socket s) : acceptor_(&a), socket_(std::move(s)) {} public: tcp::socket operator*() { return std::move(socket_); } awaitable<void> operator++() { socket_ = co_await acceptor_->async_accept(use_awaitable); } bool operator==(const connection_iter&) const noexcept { return false; } bool operator!=(const connection_iter&) const noexcept { return true; } }; class connections { tcp::acceptor& acceptor_; public: explicit connections(tcp::acceptor& a) : acceptor_(a) {} awaitable<connection_iter> begin() { tcp::socket s = co_await acceptor_.async_accept(use_awaitable); co_return connection_iter(acceptor_, std::move(s)); } connection_iter end() { return connection_iter(acceptor_, tcp::socket(acceptor_.get_executor())); } }; awaitable<void> listener(tcp::acceptor acceptor) { for co_await (tcp::socket s : connections(acceptor)) { co_await boost::asio::async_write(s, boost::asio::buffer("hello\r\n", 7), use_awaitable); } } int main() { try { boost::asio::io_context io_context(1); boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); co_spawn(io_context, listener(std::move(acceptor)), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/refactored_echo_server.cpp
// // refactored_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdio> using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::use_awaitable; namespace this_coro = boost::asio::this_coro; awaitable<void> echo_once(tcp::socket& socket) { char data[128]; std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), use_awaitable); co_await async_write(socket, boost::asio::buffer(data, n), use_awaitable); } awaitable<void> echo(tcp::socket socket) { try { for (;;) { // The asynchronous operations to echo a single chunk of data have been // refactored into a separate function. When this function is called, the // operations are still performed in the context of the current // coroutine, and the behaviour is functionally equivalent. co_await echo_once(socket); } } catch (std::exception& e) { std::printf("echo Exception: %s\n", e.what()); } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { tcp::socket socket = co_await acceptor.async_accept(use_awaitable); co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { boost::asio::io_context io_context(1); boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/echo_server_with_default.cpp
// // echo_server_with_default.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdio> using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::use_awaitable_t; using tcp_acceptor = use_awaitable_t<>::as_default_on_t<tcp::acceptor>; using tcp_socket = use_awaitable_t<>::as_default_on_t<tcp::socket>; namespace this_coro = boost::asio::this_coro; awaitable<void> echo(tcp_socket socket) { try { char data[1024]; for (;;) { std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data)); co_await async_write(socket, boost::asio::buffer(data, n)); } } catch (std::exception& e) { std::printf("echo Exception: %s\n", e.what()); } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp_acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { auto socket = co_await acceptor.async_accept(); co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { boost::asio::io_context io_context(1); boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/echo_server_with_as_tuple_default.cpp
// // echo_server_with_as_tuple_default.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/as_tuple.hpp> #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdio> using boost::asio::as_tuple_t; using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::use_awaitable_t; using default_token = as_tuple_t<use_awaitable_t<>>; using tcp_acceptor = default_token::as_default_on_t<tcp::acceptor>; using tcp_socket = default_token::as_default_on_t<tcp::socket>; namespace this_coro = boost::asio::this_coro; awaitable<void> echo(tcp_socket socket) { char data[1024]; for (;;) { auto [e1, nread] = co_await socket.async_read_some(boost::asio::buffer(data)); if (nread == 0) break; auto [e2, nwritten] = co_await async_write(socket, boost::asio::buffer(data, nread)); if (nwritten != nread) break; } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp_acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { if (auto [e, socket] = co_await acceptor.async_accept(); socket.is_open()) co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { boost::asio::io_context io_context(1); boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/echo_server.cpp
// // echo_server.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdio> using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::use_awaitable; namespace this_coro = boost::asio::this_coro; #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) # define use_awaitable \ boost::asio::use_awaitable_t(__FILE__, __LINE__, __PRETTY_FUNCTION__) #endif awaitable<void> echo(tcp::socket socket) { try { char data[1024]; for (;;) { std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), use_awaitable); co_await async_write(socket, boost::asio::buffer(data, n), use_awaitable); } } catch (std::exception& e) { std::printf("echo Exception: %s\n", e.what()); } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { tcp::socket socket = co_await acceptor.async_accept(use_awaitable); co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { boost::asio::io_context io_context(1); boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
cpp
asio
data/projects/asio/example/cpp17/coroutines_ts/echo_server_with_as_single_default.cpp
// // echo_server_with_as_single_default.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/experimental/as_single.hpp> #include <boost/asio/co_spawn.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdio> using boost::asio::experimental::as_single_t; using boost::asio::ip::tcp; using boost::asio::awaitable; using boost::asio::co_spawn; using boost::asio::detached; using boost::asio::use_awaitable_t; using default_token = as_single_t<use_awaitable_t<>>; using tcp_acceptor = default_token::as_default_on_t<tcp::acceptor>; using tcp_socket = default_token::as_default_on_t<tcp::socket>; namespace this_coro = boost::asio::this_coro; awaitable<void> echo(tcp_socket socket) { char data[1024]; for (;;) { auto [e1, nread] = co_await socket.async_read_some(boost::asio::buffer(data)); if (nread == 0) break; auto [e2, nwritten] = co_await async_write(socket, boost::asio::buffer(data, nread)); if (nwritten != nread) break; } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp_acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { if (auto [e, socket] = co_await acceptor.async_accept(); socket.is_open()) co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { boost::asio::io_context io_context(1); boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
cpp
asio
data/projects/asio/example/cpp11/ssl/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <functional> #include <iostream> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> using boost::asio::ip::tcp; class session : public std::enable_shared_from_this<session> { public: session(boost::asio::ssl::stream<tcp::socket> socket) : socket_(std::move(socket)) { } void start() { do_handshake(); } private: void do_handshake() { auto self(shared_from_this()); socket_.async_handshake(boost::asio::ssl::stream_base::server, [this, self](const boost::system::error_code& error) { if (!error) { do_read(); } }); } void do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(data_), [this, self](const boost::system::error_code& ec, std::size_t length) { if (!ec) { do_write(length); } }); } void do_write(std::size_t length) { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [this, self](const boost::system::error_code& ec, std::size_t /*length*/) { if (!ec) { do_read(); } }); } boost::asio::ssl::stream<tcp::socket> socket_; char data_[1024]; }; class server { public: server(boost::asio::io_context& io_context, unsigned short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)), context_(boost::asio::ssl::context::sslv23) { context_.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); context_.set_password_callback(std::bind(&server::get_password, this)); context_.use_certificate_chain_file("server.pem"); context_.use_private_key_file("server.pem", boost::asio::ssl::context::pem); context_.use_tmp_dh_file("dh4096.pem"); do_accept(); } private: std::string get_password() const { return "test"; } void do_accept() { acceptor_.async_accept( [this](const boost::system::error_code& error, tcp::socket socket) { if (!error) { std::make_shared<session>( boost::asio::ssl::stream<tcp::socket>( std::move(socket), context_))->start(); } do_accept(); }); } tcp::acceptor acceptor_; boost::asio::ssl::context context_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: server <port>\n"; return 1; } boost::asio::io_context io_context; using namespace std; // For atoi. server s(io_context, atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/ssl/client.cpp
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> using boost::asio::ip::tcp; using std::placeholders::_1; using std::placeholders::_2; enum { max_length = 1024 }; class client { public: client(boost::asio::io_context& io_context, boost::asio::ssl::context& context, const tcp::resolver::results_type& endpoints) : socket_(io_context, context) { socket_.set_verify_mode(boost::asio::ssl::verify_peer); socket_.set_verify_callback( std::bind(&client::verify_certificate, this, _1, _2)); connect(endpoints); } private: bool verify_certificate(bool preverified, boost::asio::ssl::verify_context& ctx) { // The verify callback can be used to check whether the certificate that is // being presented is valid for the peer. For example, RFC 2818 describes // the steps involved in doing this for HTTPS. Consult the OpenSSL // documentation for more details. Note that the callback is called once // for each certificate in the certificate chain, starting from the root // certificate authority. // In this example we will simply print the certificate's subject name. char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "Verifying " << subject_name << "\n"; return preverified; } void connect(const tcp::resolver::results_type& endpoints) { boost::asio::async_connect(socket_.lowest_layer(), endpoints, [this](const boost::system::error_code& error, const tcp::endpoint& /*endpoint*/) { if (!error) { handshake(); } else { std::cout << "Connect failed: " << error.message() << "\n"; } }); } void handshake() { socket_.async_handshake(boost::asio::ssl::stream_base::client, [this](const boost::system::error_code& error) { if (!error) { send_request(); } else { std::cout << "Handshake failed: " << error.message() << "\n"; } }); } void send_request() { std::cout << "Enter message: "; std::cin.getline(request_, max_length); size_t request_length = std::strlen(request_); boost::asio::async_write(socket_, boost::asio::buffer(request_, request_length), [this](const boost::system::error_code& error, std::size_t length) { if (!error) { receive_response(length); } else { std::cout << "Write failed: " << error.message() << "\n"; } }); } void receive_response(std::size_t length) { boost::asio::async_read(socket_, boost::asio::buffer(reply_, length), [this](const boost::system::error_code& error, std::size_t length) { if (!error) { std::cout << "Reply: "; std::cout.write(reply_, length); std::cout << "\n"; } else { std::cout << "Read failed: " << error.message() << "\n"; } }); } boost::asio::ssl::stream<tcp::socket> socket_; char request_[max_length]; char reply_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: client <host> <port>\n"; return 1; } boost::asio::io_context io_context; tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23); ctx.load_verify_file("ca.pem"); client c(io_context, ctx, endpoints); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/echo/blocking_udp_echo_server.cpp
// // blocking_udp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::udp; enum { max_length = 1024 }; void server(boost::asio::io_context& io_context, unsigned short port) { udp::socket sock(io_context, udp::endpoint(udp::v4(), port)); for (;;) { char data[max_length]; udp::endpoint sender_endpoint; size_t length = sock.receive_from( boost::asio::buffer(data, max_length), sender_endpoint); sock.send_to(boost::asio::buffer(data, length), sender_endpoint); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: blocking_udp_echo_server <port>\n"; return 1; } boost::asio::io_context io_context; server(io_context, std::atoi(argv[1])); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/echo/blocking_tcp_echo_client.cpp
// // blocking_tcp_echo_client.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <cstring> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::tcp; enum { max_length = 1024 }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n"; return 1; } boost::asio::io_context io_context; tcp::socket s(io_context); tcp::resolver resolver(io_context); boost::asio::connect(s, resolver.resolve(argv[1], argv[2])); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); boost::asio::write(s, boost::asio::buffer(request, request_length)); char reply[max_length]; size_t reply_length = boost::asio::read(s, boost::asio::buffer(reply, request_length)); std::cout << "Reply is: "; std::cout.write(reply, reply_length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/echo/blocking_udp_echo_client.cpp
// // blocking_udp_echo_client.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <cstring> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::udp; enum { max_length = 1024 }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n"; return 1; } boost::asio::io_context io_context; udp::socket s(io_context, udp::endpoint(udp::v4(), 0)); udp::resolver resolver(io_context); udp::resolver::results_type endpoints = resolver.resolve(udp::v4(), argv[1], argv[2]); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); s.send_to(boost::asio::buffer(request, request_length), *endpoints.begin()); char reply[max_length]; udp::endpoint sender_endpoint; size_t reply_length = s.receive_from( boost::asio::buffer(reply, max_length), sender_endpoint); std::cout << "Reply is: "; std::cout.write(reply, reply_length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/echo/blocking_tcp_echo_server.cpp
// // blocking_tcp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <thread> #include <utility> #include <boost/asio.hpp> using boost::asio::ip::tcp; const int max_length = 1024; void session(tcp::socket sock) { try { for (;;) { char data[max_length]; boost::system::error_code error; size_t length = sock.read_some(boost::asio::buffer(data), error); if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw boost::system::system_error(error); // Some other error. boost::asio::write(sock, boost::asio::buffer(data, length)); } } catch (std::exception& e) { std::cerr << "Exception in thread: " << e.what() << "\n"; } } void server(boost::asio::io_context& io_context, unsigned short port) { tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port)); for (;;) { std::thread(session, a.accept()).detach(); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: blocking_tcp_echo_server <port>\n"; return 1; } boost::asio::io_context io_context; server(io_context, std::atoi(argv[1])); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/echo/async_udp_echo_server.cpp
// // async_udp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::udp; class server { public: server(boost::asio::io_context& io_context, short port) : socket_(io_context, udp::endpoint(udp::v4(), port)) { do_receive(); } void do_receive() { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, [this](boost::system::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { do_send(bytes_recvd); } else { do_receive(); } }); } void do_send(std::size_t length) { socket_.async_send_to( boost::asio::buffer(data_, length), sender_endpoint_, [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) { do_receive(); }); } private: udp::socket socket_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_udp_echo_server <port>\n"; return 1; } boost::asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/echo/async_tcp_echo_server.cpp
// // async_tcp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <memory> #include <utility> #include <boost/asio.hpp> using boost::asio::ip::tcp; class session : public std::enable_shared_from_this<session> { public: session(tcp::socket socket) : socket_(std::move(socket)) { } void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(data_, max_length), [this, self](boost::system::error_code ec, std::size_t length) { if (!ec) { do_write(length); } }); } void do_write(std::size_t length) { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { do_read(); } }); } tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(boost::asio::io_context& io_context, short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](boost::system::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } boost::asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/futures/daytime_client.cpp
// // daytime_client.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <future> #include <iostream> #include <thread> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/use_future.hpp> using boost::asio::ip::udp; void get_daytime(boost::asio::io_context& io_context, const char* hostname) { try { udp::resolver resolver(io_context); std::future<udp::resolver::results_type> endpoints = resolver.async_resolve( udp::v4(), hostname, "daytime", boost::asio::use_future); // The async_resolve operation above returns the endpoints as a future // value that is not retrieved ... udp::socket socket(io_context, udp::v4()); std::array<char, 1> send_buf = {{ 0 }}; std::future<std::size_t> send_length = socket.async_send_to(boost::asio::buffer(send_buf), *endpoints.get().begin(), // ... until here. This call may block. boost::asio::use_future); // Do other things here while the send completes. send_length.get(); // Blocks until the send is complete. Throws any errors. std::array<char, 128> recv_buf; udp::endpoint sender_endpoint; std::future<std::size_t> recv_length = socket.async_receive_from( boost::asio::buffer(recv_buf), sender_endpoint, boost::asio::use_future); // Do other things here while the receive completes. std::cout.write( recv_buf.data(), recv_length.get()); // Blocks until receive is complete. } catch (boost::system::system_error& e) { std::cerr << e.what() << std::endl; } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: daytime_client <host>" << std::endl; return 1; } // We run the io_context off in its own thread so that it operates // completely asynchronously with respect to the rest of the program. boost::asio::io_context io_context; auto work = boost::asio::make_work_guard(io_context); std::thread thread([&io_context](){ io_context.run(); }); get_daytime(io_context, argv[1]); io_context.stop(); thread.join(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/services/basic_logger.hpp
// // basic_logger.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef SERVICES_BASIC_LOGGER_HPP #define SERVICES_BASIC_LOGGER_HPP #include <boost/asio.hpp> #include <string> namespace services { /// Class to provide simple logging functionality. Use the services::logger /// typedef. template <typename Service> class basic_logger { public: /// The type of the service that will be used to provide timer operations. typedef Service service_type; /// The native implementation type of the timer. typedef typename service_type::impl_type impl_type; /// Constructor. /** * This constructor creates a logger. * * @param context The execution context used to locate the logger service. * * @param identifier An identifier for this logger. */ explicit basic_logger(boost::asio::execution_context& context, const std::string& identifier) : service_(boost::asio::use_service<Service>(context)), impl_(service_.null()) { service_.create(impl_, identifier); } basic_logger(const basic_logger&) = delete; basic_logger& operator=(basic_logger&) = delete; /// Destructor. ~basic_logger() { service_.destroy(impl_); } /// Set the output file for all logger instances. void use_file(const std::string& file) { service_.use_file(impl_, file); } /// Log a message. void log(const std::string& message) { service_.log(impl_, message); } private: /// The backend service implementation. service_type& service_; /// The underlying native implementation. impl_type impl_; }; } // namespace services #endif // SERVICES_BASIC_LOGGER_HPP
hpp
asio
data/projects/asio/example/cpp11/services/logger.hpp
// // logger.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef SERVICES_LOGGER_HPP #define SERVICES_LOGGER_HPP #include "basic_logger.hpp" #include "logger_service.hpp" namespace services { /// Typedef for typical logger usage. typedef basic_logger<logger_service> logger; } // namespace services #endif // SERVICES_LOGGER_HPP
hpp
asio
data/projects/asio/example/cpp11/services/logger_service.cpp
// // logger_service.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "logger_service.hpp"
cpp
asio
data/projects/asio/example/cpp11/services/logger_service.hpp
// // logger_service.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef SERVICES_LOGGER_SERVICE_HPP #define SERVICES_LOGGER_SERVICE_HPP #include <boost/asio.hpp> #include <functional> #include <fstream> #include <sstream> #include <string> #include <thread> namespace services { /// Service implementation for the logger. class logger_service : public boost::asio::execution_context::service { public: /// The type used to identify this service in the execution context. typedef logger_service key_type; /// The backend implementation of a logger. struct logger_impl { explicit logger_impl(const std::string& ident) : identifier(ident) {} std::string identifier; }; /// The type for an implementation of the logger. typedef logger_impl* impl_type; /// Constructor creates a thread to run a private io_context. logger_service(boost::asio::execution_context& context) : boost::asio::execution_context::service(context), work_io_context_(), work_(boost::asio::make_work_guard(work_io_context_)), work_thread_([this]{ work_io_context_.run(); }) { } logger_service(const logger_service&) = delete; logger_service& operator=(const logger_service&) = delete;; /// Destructor shuts down the private io_context. ~logger_service() { /// Indicate that we have finished with the private io_context. Its /// io_context::run() function will exit once all other work has completed. work_.reset(); if (work_thread_.joinable()) work_thread_.join(); } /// Destroy all user-defined handler objects owned by the service. void shutdown() { } /// Return a null logger implementation. impl_type null() const { return 0; } /// Create a new logger implementation. void create(impl_type& impl, const std::string& identifier) { impl = new logger_impl(identifier); } /// Destroy a logger implementation. void destroy(impl_type& impl) { delete impl; impl = null(); } /// Set the output file for the logger. The current implementation sets the /// output file for all logger instances, and so the impl parameter is not /// actually needed. It is retained here to illustrate how service functions /// are typically defined. void use_file(impl_type& /*impl*/, const std::string& file) { // Pass the work of opening the file to the background thread. boost::asio::post(work_io_context_, std::bind(&logger_service::use_file_impl, this, file)); } /// Log a message. void log(impl_type& impl, const std::string& message) { // Format the text to be logged. std::ostringstream os; os << impl->identifier << ": " << message; // Pass the work of writing to the file to the background thread. boost::asio::post(work_io_context_, std::bind(&logger_service::log_impl, this, os.str())); } private: /// Helper function used to open the output file from within the private /// io_context's thread. void use_file_impl(const std::string& file) { ofstream_.close(); ofstream_.clear(); ofstream_.open(file.c_str()); } /// Helper function used to log a message from within the private io_context's /// thread. void log_impl(const std::string& text) { ofstream_ << text << std::endl; } /// Private io_context used for performing logging operations. boost::asio::io_context work_io_context_; /// Work for the private io_context to perform. If we do not give the /// io_context some work to do then the io_context::run() function will exit /// immediately. boost::asio::executor_work_guard< boost::asio::io_context::executor_type> work_; /// Thread used for running the work io_context's run loop. std::thread work_thread_; /// The file to which log messages will be written. std::ofstream ofstream_; }; } // namespace services #endif // SERVICES_LOGGER_SERVICE_HPP
hpp
asio
data/projects/asio/example/cpp11/services/daytime_client.cpp
// // daytime_client.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <functional> #include <iostream> #include "logger.hpp" using boost::asio::ip::tcp; char read_buffer[1024]; void read_handler(const boost::system::error_code& e, std::size_t bytes_transferred, tcp::socket* s) { if (!e) { std::cout.write(read_buffer, bytes_transferred); s->async_read_some(boost::asio::buffer(read_buffer), std::bind(read_handler, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, s)); } else { boost::asio::execution_context& context = boost::asio::query( s->get_executor(), boost::asio::execution::context); services::logger logger(context, "read_handler"); std::string msg = "Read error: "; msg += e.message(); logger.log(msg); } } void connect_handler(const boost::system::error_code& e, tcp::socket* s) { boost::asio::execution_context& context = boost::asio::query( s->get_executor(), boost::asio::execution::context); services::logger logger(context, "connect_handler"); if (!e) { logger.log("Connection established"); s->async_read_some(boost::asio::buffer(read_buffer), std::bind(read_handler, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, s)); } else { std::string msg = "Unable to establish connection: "; msg += e.message(); logger.log(msg); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: daytime_client <host>" << std::endl; return 1; } boost::asio::io_context io_context; // Set the name of the file that all logger instances will use. services::logger logger(io_context, ""); logger.use_file("log.txt"); // Resolve the address corresponding to the given host. tcp::resolver resolver(io_context); tcp::resolver::results_type endpoints = resolver.resolve(argv[1], "daytime"); // Start an asynchronous connect. tcp::socket socket(io_context); boost::asio::async_connect(socket, endpoints, std::bind(connect_handler, boost::asio::placeholders::error, &socket)); // Run the io_context until all operations have finished. io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/nonblocking/third_party_lib.cpp
// // third_party_lib.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <array> #include <iostream> #include <memory> using boost::asio::ip::tcp; namespace third_party_lib { // Simulation of a third party library that wants to perform read and write // operations directly on a socket. It needs to be polled to determine whether // it requires a read or write operation, and notified when the socket is ready // for reading or writing. class session { public: session(tcp::socket& socket) : socket_(socket) { } // Returns true if the third party library wants to be notified when the // socket is ready for reading. bool want_read() const { return state_ == reading; } // Notify that third party library that it should perform its read operation. void do_read(boost::system::error_code& ec) { if (std::size_t len = socket_.read_some(boost::asio::buffer(data_), ec)) { write_buffer_ = boost::asio::buffer(data_, len); state_ = writing; } } // Returns true if the third party library wants to be notified when the // socket is ready for writing. bool want_write() const { return state_ == writing; } // Notify that third party library that it should perform its write operation. void do_write(boost::system::error_code& ec) { if (std::size_t len = socket_.write_some( boost::asio::buffer(write_buffer_), ec)) { write_buffer_ = write_buffer_ + len; state_ = boost::asio::buffer_size(write_buffer_) > 0 ? writing : reading; } } private: tcp::socket& socket_; enum { reading, writing } state_ = reading; std::array<char, 128> data_; boost::asio::const_buffer write_buffer_; }; } // namespace third_party_lib // The glue between asio's sockets and the third party library. class connection : public std::enable_shared_from_this<connection> { public: connection(tcp::socket socket) : socket_(std::move(socket)) { } void start() { // Put the socket into non-blocking mode. socket_.non_blocking(true); do_operations(); } private: void do_operations() { auto self(shared_from_this()); // Start a read operation if the third party library wants one. if (session_impl_.want_read() && !read_in_progress_) { read_in_progress_ = true; socket_.async_wait(tcp::socket::wait_read, [this, self](boost::system::error_code ec) { read_in_progress_ = false; // Notify third party library that it can perform a read. if (!ec) session_impl_.do_read(ec); // The third party library successfully performed a read on the // socket. Start new read or write operations based on what it now // wants. if (!ec || ec == boost::asio::error::would_block) do_operations(); // Otherwise, an error occurred. Closing the socket cancels any // outstanding asynchronous read or write operations. The // connection object will be destroyed automatically once those // outstanding operations complete. else socket_.close(); }); } // Start a write operation if the third party library wants one. if (session_impl_.want_write() && !write_in_progress_) { write_in_progress_ = true; socket_.async_wait(tcp::socket::wait_write, [this, self](boost::system::error_code ec) { write_in_progress_ = false; // Notify third party library that it can perform a write. if (!ec) session_impl_.do_write(ec); // The third party library successfully performed a write on the // socket. Start new read or write operations based on what it now // wants. if (!ec || ec == boost::asio::error::would_block) do_operations(); // Otherwise, an error occurred. Closing the socket cancels any // outstanding asynchronous read or write operations. The // connection object will be destroyed automatically once those // outstanding operations complete. else socket_.close(); }); } } private: tcp::socket socket_; third_party_lib::session session_impl_{socket_}; bool read_in_progress_ = false; bool write_in_progress_ = false; }; class server { public: server(boost::asio::io_context& io_context, unsigned short port) : acceptor_(io_context, {tcp::v4(), port}) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](boost::system::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<connection>(std::move(socket))->start(); } do_accept(); }); } tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: third_party_lib <port>\n"; return 1; } boost::asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_4.cpp
// // composed_4.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/bind_executor.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <cstring> #include <functional> #include <iostream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // In this composed operation we repackage an existing operation, but with a // different completion handler signature. We will also intercept an empty // message as an invalid argument, and propagate the corresponding error to the // user. The asynchronous operation requirements are met by delegating // responsibility to the underlying operation. // In addition to determining the mechanism by which an asynchronous operation // delivers its result, a completion token also determines the time when the // operation commences. For example, when the completion token is a simple // callback the operation commences before the initiating function returns. // However, if the completion token's delivery mechanism uses a future, we // might instead want to defer initiation of the operation until the returned // future object is waited upon. // // To enable this, when implementing an asynchronous operation we must package // the initiation step as a function object. struct async_write_message_initiation { // The initiation function object's call operator is passed the concrete // completion handler produced by the completion token. This completion // handler matches the asynchronous operation's completion handler signature, // which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments as members in the initiaton function object. However, we should // prefer to propagate them as function call arguments as this allows the // completion token to optimise how they are passed. For example, a lazy // future which defers initiation would need to make a decay-copy of the // arguments, but when using a simple callback the arguments can be trivially // forwarded straight through.) template <typename CompletionHandler> void operator()(CompletionHandler&& completion_handler, tcp::socket& socket, const char* message) const { // The post operation has a completion handler signature of: // // void() // // and the async_write operation has a completion handler signature of: // // void(boost::system::error_code error, std::size n) // // Both of these operations' completion handler signatures differ from our // operation's completion handler signature. We will adapt our completion // handler to these signatures by using std::bind, which drops the // additional arguments. // // However, it is essential to the correctness of our composed operation // that we preserve the executor of the user-supplied completion handler. // The std::bind function will not do this for us, so we must do this by // first obtaining the completion handler's associated executor (defaulting // to the I/O executor - in this case the executor of the socket - if the // completion handler does not have its own) ... auto executor = boost::asio::get_associated_executor( completion_handler, socket.get_executor()); // ... and then binding this executor to our adapted completion handler // using the boost::asio::bind_executor function. std::size_t length = std::strlen(message); if (length == 0) { boost::asio::post( boost::asio::bind_executor(executor, std::bind(std::forward<CompletionHandler>(completion_handler), boost::asio::error::invalid_argument))); } else { boost::asio::async_write(socket, boost::asio::buffer(message, length), boost::asio::bind_executor(executor, std::bind(std::forward<CompletionHandler>(completion_handler), std::placeholders::_1))); } } }; template <typename CompletionToken> auto async_write_message(tcp::socket& socket, const char* message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_initiate. -> decltype( boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), message)) { // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), message); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, "", [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, "", boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_message( socket, "", boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Message sent\n"; } catch (const std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_2.cpp
// // composed_2.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <cstring> #include <iostream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This next simplest example of a composed asynchronous operation involves // repackaging multiple operations but choosing to invoke just one of them. All // of these underlying operations have the same completion signature. The // asynchronous operation requirements are met by delegating responsibility to // the underlying operations. // In addition to determining the mechanism by which an asynchronous operation // delivers its result, a completion token also determines the time when the // operation commences. For example, when the completion token is a simple // callback the operation commences before the initiating function returns. // However, if the completion token's delivery mechanism uses a future, we // might instead want to defer initiation of the operation until the returned // future object is waited upon. // // To enable this, when implementing an asynchronous operation we must package // the initiation step as a function object. struct async_write_message_initiation { // The initiation function object's call operator is passed the concrete // completion handler produced by the completion token. This completion // handler matches the asynchronous operation's completion handler signature, // which in this example is: // // void(boost::system::error_code error, std::size_t) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments as members in the initiaton function object. However, we should // prefer to propagate them as function call arguments as this allows the // completion token to optimise how they are passed. For example, a lazy // future which defers initiation would need to make a decay-copy of the // arguments, but when using a simple callback the arguments can be trivially // forwarded straight through.) template <typename CompletionHandler> void operator()(CompletionHandler&& completion_handler, tcp::socket& socket, const char* message, bool allow_partial_write) const { if (allow_partial_write) { // When delegating to an underlying operation we must take care to // perfectly forward the completion handler. This ensures that our // operation works correctly with move-only function objects as // callbacks. return socket.async_write_some( boost::asio::buffer(message, std::strlen(message)), std::forward<CompletionHandler>(completion_handler)); } else { // As above, we must perfectly forward the completion handler when calling // the alternate underlying operation. return boost::asio::async_write(socket, boost::asio::buffer(message, std::strlen(message)), std::forward<CompletionHandler>(completion_handler)); } } }; template <typename CompletionToken> auto async_write_message(tcp::socket& socket, const char* message, bool allow_partial_write, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is void. // However, when the completion token is boost::asio::yield_context (used for // stackful coroutines) the return type would be std::size_t, and when the // completion token is boost::asio::use_future it would be std::future<std::size_t>. // When the completion token is boost::asio::deferred, the return type differs for // each asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_initiate. -> decltype( boost::asio::async_initiate< CompletionToken, void(boost::system::error_code, std::size_t)>( async_write_message_initiation(), token, std::ref(socket), message, allow_partial_write)) { // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code, std::size_t)>( async_write_message_initiation(), token, std::ref(socket), message, allow_partial_write); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, "Testing callback\r\n", false, [](const boost::system::error_code& error, std::size_t n) { if (!error) { std::cout << n << " bytes transferred\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, "Testing deferred\r\n", false, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error, std::size_t n) { if (!error) { std::cout << n << " bytes transferred\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<std::size_t> f = async_write_message( socket, "Testing future\r\n", false, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. std::size_t n = f.get(); std::cout << n << " bytes transferred\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_6.cpp
// // composed_6.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/executor_work_guard.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation shows composition of multiple underlying operations. // It automatically serialises a message, using its I/O streams insertion // operator, before sending it N times on the socket. To do this, it must // allocate a buffer for the encoded message and ensure this buffer's validity // until all underlying async_write operation complete. A one second delay is // inserted prior to each write operation, using a steady_timer. // In addition to determining the mechanism by which an asynchronous operation // delivers its result, a completion token also determines the time when the // operation commences. For example, when the completion token is a simple // callback the operation commences before the initiating function returns. // However, if the completion token's delivery mechanism uses a future, we // might instead want to defer initiation of the operation until the returned // future object is waited upon. // // To enable this, when implementing an asynchronous operation we must package // the initiation step as a function object. struct async_write_message_initiation { // The initiation function object's call operator is passed the concrete // completion handler produced by the completion token. This completion // handler matches the asynchronous operation's completion handler signature, // which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments as members in the initiaton function object. However, we should // prefer to propagate them as function call arguments as this allows the // completion token to optimise how they are passed. For example, a lazy // future which defers initiation would need to make a decay-copy of the // arguments, but when using a simple callback the arguments can be trivially // forwarded straight through.) template <typename CompletionHandler> void operator()(CompletionHandler&& completion_handler, tcp::socket& socket, std::unique_ptr<std::string> encoded_message, std::size_t repeat_count, std::unique_ptr<boost::asio::steady_timer> delay_timer) const { // In this example, the composed operation's intermediate completion // handler is implemented as a hand-crafted function object. struct intermediate_completion_handler { // The intermediate completion handler holds a reference to the socket as // it is used for multiple async_write operations, as well as for // obtaining the I/O executor (see get_executor below). tcp::socket& socket_; // The allocated buffer for the encoded message. The std::unique_ptr // smart pointer is move-only, and as a consequence our intermediate // completion handler is also move-only. std::unique_ptr<std::string> encoded_message_; // The repeat count remaining. std::size_t repeat_count_; // A steady timer used for introducing a delay. std::unique_ptr<boost::asio::steady_timer> delay_timer_; // To manage the cycle between the multiple underlying asychronous // operations, our intermediate completion handler is implemented as a // state machine. enum { starting, waiting, writing } state_; // As our composed operation performs multiple underlying I/O operations, // we should maintain a work object against the I/O executor. This tells // the I/O executor that there is still more work to come in the future. boost::asio::executor_work_guard<tcp::socket::executor_type> io_work_; // The user-supplied completion handler, called once only on completion // of the entire composed operation. typename std::decay<CompletionHandler>::type handler_; // By having a default value for the second argument, this function call // operator matches the completion signature of both the async_write and // steady_timer::async_wait operations. void operator()(const boost::system::error_code& error, std::size_t = 0) { if (!error) { switch (state_) { case starting: case writing: if (repeat_count_ > 0) { --repeat_count_; state_ = waiting; delay_timer_->expires_after(std::chrono::seconds(1)); delay_timer_->async_wait(std::move(*this)); return; // Composed operation not yet complete. } break; // Composed operation complete, continue below. case waiting: state_ = writing; boost::asio::async_write(socket_, boost::asio::buffer(*encoded_message_), std::move(*this)); return; // Composed operation not yet complete. } } // This point is reached only on completion of the entire composed // operation. // We no longer have any future work coming for the I/O executor. io_work_.reset(); // Deallocate the encoded message before calling the user-supplied // completion handler. encoded_message_.reset(); // Call the user-supplied handler with the result of the operation. handler_(error); } // It is essential to the correctness of our composed operation that we // preserve the executor of the user-supplied completion handler. With a // hand-crafted function object we can do this by defining a nested type // executor_type and member function get_executor. These obtain the // completion handler's associated executor, and default to the I/O // executor - in this case the executor of the socket - if the completion // handler does not have its own. using executor_type = boost::asio::associated_executor_t< typename std::decay<CompletionHandler>::type, tcp::socket::executor_type>; executor_type get_executor() const noexcept { return boost::asio::get_associated_executor( handler_, socket_.get_executor()); } // Although not necessary for correctness, we may also preserve the // allocator of the user-supplied completion handler. This is achieved by // defining a nested type allocator_type and member function // get_allocator. These obtain the completion handler's associated // allocator, and default to std::allocator<void> if the completion // handler does not have its own. using allocator_type = boost::asio::associated_allocator_t< typename std::decay<CompletionHandler>::type, std::allocator<void>>; allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator( handler_, std::allocator<void>{}); } }; // Initiate the underlying async_write operation using our intermediate // completion handler. auto encoded_message_buffer = boost::asio::buffer(*encoded_message); boost::asio::async_write(socket, encoded_message_buffer, intermediate_completion_handler{ socket, std::move(encoded_message), repeat_count, std::move(delay_timer), intermediate_completion_handler::starting, boost::asio::make_work_guard(socket.get_executor()), std::forward<CompletionHandler>(completion_handler)}); } }; template <typename T, typename CompletionToken> auto async_write_messages(tcp::socket& socket, const T& message, std::size_t repeat_count, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_initiate. -> decltype( boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), std::declval<std::unique_ptr<std::string>>(), repeat_count, std::declval<std::unique_ptr<boost::asio::steady_timer>>())) { // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the composed asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // Create a steady_timer to be used for the delay between messages. std::unique_ptr<boost::asio::steady_timer> delay_timer( new boost::asio::steady_timer(socket.get_executor())); // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), std::move(encoded_message), repeat_count, std::move(delay_timer)); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_messages(socket, "Testing callback\r\n", 5, [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_messages(socket, "Testing deferred\r\n", 5, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_messages( socket, "Testing future\r\n", 5, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Messages sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_3.cpp
// // composed_3.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/bind_executor.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <cstring> #include <functional> #include <iostream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // In this composed operation we repackage an existing operation, but with a // different completion handler signature. The asynchronous operation // requirements are met by delegating responsibility to the underlying // operation. // In addition to determining the mechanism by which an asynchronous operation // delivers its result, a completion token also determines the time when the // operation commences. For example, when the completion token is a simple // callback the operation commences before the initiating function returns. // However, if the completion token's delivery mechanism uses a future, we // might instead want to defer initiation of the operation until the returned // future object is waited upon. // // To enable this, when implementing an asynchronous operation we must package // the initiation step as a function object. struct async_write_message_initiation { // The initiation function object's call operator is passed the concrete // completion handler produced by the completion token. This completion // handler matches the asynchronous operation's completion handler signature, // which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments as members in the initiaton function object. However, we should // prefer to propagate them as function call arguments as this allows the // completion token to optimise how they are passed. For example, a lazy // future which defers initiation would need to make a decay-copy of the // arguments, but when using a simple callback the arguments can be trivially // forwarded straight through.) template <typename CompletionHandler> void operator()(CompletionHandler&& completion_handler, tcp::socket& socket, const char* message) const { // The async_write operation has a completion handler signature of: // // void(boost::system::error_code error, std::size n) // // This differs from our operation's signature in that it is also passed // the number of bytes transferred as an argument of type std::size_t. We // will adapt our completion handler to async_write's completion handler // signature by using std::bind, which drops the additional argument. // // However, it is essential to the correctness of our composed operation // that we preserve the executor of the user-supplied completion handler. // The std::bind function will not do this for us, so we must do this by // first obtaining the completion handler's associated executor (defaulting // to the I/O executor - in this case the executor of the socket - if the // completion handler does not have its own) ... auto executor = boost::asio::get_associated_executor( completion_handler, socket.get_executor()); // ... and then binding this executor to our adapted completion handler // using the boost::asio::bind_executor function. boost::asio::async_write(socket, boost::asio::buffer(message, std::strlen(message)), boost::asio::bind_executor(executor, std::bind(std::forward<CompletionHandler>( completion_handler), std::placeholders::_1))); } }; template <typename CompletionToken> auto async_write_message(tcp::socket& socket, const char* message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_initiate. -> decltype( boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), message)) { // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), message); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, "Testing callback\r\n", [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, "Testing deferred\r\n", boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_message( socket, "Testing future\r\n", boost::asio::use_future); io_context.run(); // Get the result of the operation. try { // Get the result of the operation. f.get(); std::cout << "Message sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_7.cpp
// // composed_7.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/compose.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_compose function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation shows composition of multiple underlying operations. // It automatically serialises a message, using its I/O streams insertion // operator, before sending it N times on the socket. To do this, it must // allocate a buffer for the encoded message and ensure this buffer's validity // until all underlying async_write operation complete. A one second delay is // inserted prior to each write operation, using a steady_timer. // In this example, the composed operation's logic is implemented as a state // machine within a hand-crafted function object. struct async_write_messages_implementation { // The implementation holds a reference to the socket as it is used for // multiple async_write operations. tcp::socket& socket_; // The allocated buffer for the encoded message. The std::unique_ptr smart // pointer is move-only, and as a consequence our implementation is also // move-only. std::unique_ptr<std::string> encoded_message_; // The repeat count remaining. std::size_t repeat_count_; // A steady timer used for introducing a delay. std::unique_ptr<boost::asio::steady_timer> delay_timer_; // To manage the cycle between the multiple underlying asychronous // operations, our implementation is a state machine. enum { starting, waiting, writing } state_; // The first argument to our function object's call operator is a reference // to the enclosing intermediate completion handler. This intermediate // completion handler is provided for us by the boost::asio::async_compose // function, and takes care of all the details required to implement a // conforming asynchronous operation. When calling an underlying asynchronous // operation, we pass it this enclosing intermediate completion handler // as the completion token. // // All arguments after the first must be defaulted to allow the state machine // to be started, as well as to allow the completion handler to match the // completion signature of both the async_write and steady_timer::async_wait // operations. template <typename Self> void operator()(Self& self, const boost::system::error_code& error = boost::system::error_code(), std::size_t = 0) { if (!error) { switch (state_) { case starting: case writing: if (repeat_count_ > 0) { --repeat_count_; state_ = waiting; delay_timer_->expires_after(std::chrono::seconds(1)); delay_timer_->async_wait(std::move(self)); return; // Composed operation not yet complete. } break; // Composed operation complete, continue below. case waiting: state_ = writing; boost::asio::async_write(socket_, boost::asio::buffer(*encoded_message_), std::move(self)); return; // Composed operation not yet complete. } } // This point is reached only on completion of the entire composed // operation. // Deallocate the encoded message and delay timer before calling the // user-supplied completion handler. encoded_message_.reset(); delay_timer_.reset(); // Call the user-supplied handler with the result of the operation. self.complete(error); } }; template <typename T, typename CompletionToken> auto async_write_messages(tcp::socket& socket, const T& message, std::size_t repeat_count, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_compose. -> decltype( boost::asio::async_compose< CompletionToken, void(boost::system::error_code)>( std::declval<async_write_messages_implementation>(), token, socket)) { // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the composed asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // Create a steady_timer to be used for the delay between messages. std::unique_ptr<boost::asio::steady_timer> delay_timer( new boost::asio::steady_timer(socket.get_executor())); // The boost::asio::async_compose function takes: // // - our asynchronous operation implementation, // - the completion token, // - the completion handler signature, and // - any I/O objects (or executors) used by the operation // // It then wraps our implementation in an intermediate completion handler // that meets the requirements of a conforming asynchronous operation. This // includes tracking outstanding work against the I/O executors associated // with the operation (in this example, this is the socket's executor). return boost::asio::async_compose< CompletionToken, void(boost::system::error_code)>( async_write_messages_implementation{ socket, std::move(encoded_message), repeat_count, std::move(delay_timer), async_write_messages_implementation::starting}, token, socket); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_messages(socket, "Testing callback\r\n", 5, [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_messages(socket, "Testing deferred\r\n", 5, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_messages( socket, "Testing future\r\n", 5, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Messages sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_8.cpp
// // composed_8.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/compose.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_compose function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation shows composition of multiple underlying operations, // using asio's stackless coroutines support to express the flow of control. It // automatically serialises a message, using its I/O streams insertion // operator, before sending it N times on the socket. To do this, it must // allocate a buffer for the encoded message and ensure this buffer's validity // until all underlying async_write operation complete. A one second delay is // inserted prior to each write operation, using a steady_timer. #include <boost/asio/yield.hpp> // In this example, the composed operation's logic is implemented as a state // machine within a hand-crafted function object. struct async_write_messages_implementation { // The implementation holds a reference to the socket as it is used for // multiple async_write operations. tcp::socket& socket_; // The allocated buffer for the encoded message. The std::unique_ptr smart // pointer is move-only, and as a consequence our implementation is also // move-only. std::unique_ptr<std::string> encoded_message_; // The repeat count remaining. std::size_t repeat_count_; // A steady timer used for introducing a delay. std::unique_ptr<boost::asio::steady_timer> delay_timer_; // The coroutine state. boost::asio::coroutine coro_; // The first argument to our function object's call operator is a reference // to the enclosing intermediate completion handler. This intermediate // completion handler is provided for us by the boost::asio::async_compose // function, and takes care of all the details required to implement a // conforming asynchronous operation. When calling an underlying asynchronous // operation, we pass it this enclosing intermediate completion handler // as the completion token. // // All arguments after the first must be defaulted to allow the state machine // to be started, as well as to allow the completion handler to match the // completion signature of both the async_write and steady_timer::async_wait // operations. template <typename Self> void operator()(Self& self, const boost::system::error_code& error = boost::system::error_code(), std::size_t = 0) { reenter (coro_) { while (repeat_count_ > 0) { --repeat_count_; delay_timer_->expires_after(std::chrono::seconds(1)); yield delay_timer_->async_wait(std::move(self)); if (error) break; yield boost::asio::async_write(socket_, boost::asio::buffer(*encoded_message_), std::move(self)); if (error) break; } // Deallocate the encoded message and delay timer before calling the // user-supplied completion handler. encoded_message_.reset(); delay_timer_.reset(); // Call the user-supplied handler with the result of the operation. self.complete(error); } } }; #include <boost/asio/unyield.hpp> template <typename T, typename CompletionToken> auto async_write_messages(tcp::socket& socket, const T& message, std::size_t repeat_count, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_compose. -> decltype( boost::asio::async_compose< CompletionToken, void(boost::system::error_code)>( std::declval<async_write_messages_implementation>(), token, socket)) { // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the composed asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // Create a steady_timer to be used for the delay between messages. std::unique_ptr<boost::asio::steady_timer> delay_timer( new boost::asio::steady_timer(socket.get_executor())); // The boost::asio::async_compose function takes: // // - our asynchronous operation implementation, // - the completion token, // - the completion handler signature, and // - any I/O objects (or executors) used by the operation // // It then wraps our implementation in an intermediate completion handler // that meets the requirements of a conforming asynchronous operation. This // includes tracking outstanding work against the I/O executors associated // with the operation (in this example, this is the socket's executor). return boost::asio::async_compose< CompletionToken, void(boost::system::error_code)>( async_write_messages_implementation{socket, std::move(encoded_message), repeat_count, std::move(delay_timer), boost::asio::coroutine()}, token, socket); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_messages(socket, "Testing callback\r\n", 5, [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_messages(socket, "Testing deferred\r\n", 5, boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Messages sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_messages( socket, "Testing future\r\n", 5, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Messages sent\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_5.cpp
// // composed_5.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; // NOTE: This example requires the new boost::asio::async_initiate function. For // an example that works with the Networking TS style of completion tokens, // please see an older version of asio. //------------------------------------------------------------------------------ // This composed operation automatically serialises a message, using its I/O // streams insertion operator, before sending it on the socket. To do this, it // must allocate a buffer for the encoded message and ensure this buffer's // validity until the underlying async_write operation completes. // In addition to determining the mechanism by which an asynchronous operation // delivers its result, a completion token also determines the time when the // operation commences. For example, when the completion token is a simple // callback the operation commences before the initiating function returns. // However, if the completion token's delivery mechanism uses a future, we // might instead want to defer initiation of the operation until the returned // future object is waited upon. // // To enable this, when implementing an asynchronous operation we must package // the initiation step as a function object. struct async_write_message_initiation { // The initiation function object's call operator is passed the concrete // completion handler produced by the completion token. This completion // handler matches the asynchronous operation's completion handler signature, // which in this example is: // // void(boost::system::error_code error) // // The initiation function object also receives any additional arguments // required to start the operation. (Note: We could have instead passed these // arguments as members in the initiaton function object. However, we should // prefer to propagate them as function call arguments as this allows the // completion token to optimise how they are passed. For example, a lazy // future which defers initiation would need to make a decay-copy of the // arguments, but when using a simple callback the arguments can be trivially // forwarded straight through.) template <typename CompletionHandler> void operator()(CompletionHandler&& completion_handler, tcp::socket& socket, std::unique_ptr<std::string> encoded_message) const { // In this example, the composed operation's intermediate completion // handler is implemented as a hand-crafted function object, rather than // using a lambda or std::bind. struct intermediate_completion_handler { // The intermediate completion handler holds a reference to the socket so // that it can obtain the I/O executor (see get_executor below). tcp::socket& socket_; // The allocated buffer for the encoded message. The std::unique_ptr // smart pointer is move-only, and as a consequence our intermediate // completion handler is also move-only. std::unique_ptr<std::string> encoded_message_; // The user-supplied completion handler. typename std::decay<CompletionHandler>::type handler_; // The function call operator matches the completion signature of the // async_write operation. void operator()(const boost::system::error_code& error, std::size_t /*n*/) { // Deallocate the encoded message before calling the user-supplied // completion handler. encoded_message_.reset(); // Call the user-supplied handler with the result of the operation. // The arguments must match the completion signature of our composed // operation. handler_(error); } // It is essential to the correctness of our composed operation that we // preserve the executor of the user-supplied completion handler. With a // hand-crafted function object we can do this by defining a nested type // executor_type and member function get_executor. These obtain the // completion handler's associated executor, and default to the I/O // executor - in this case the executor of the socket - if the completion // handler does not have its own. using executor_type = boost::asio::associated_executor_t< typename std::decay<CompletionHandler>::type, tcp::socket::executor_type>; executor_type get_executor() const noexcept { return boost::asio::get_associated_executor( handler_, socket_.get_executor()); } // Although not necessary for correctness, we may also preserve the // allocator of the user-supplied completion handler. This is achieved by // defining a nested type allocator_type and member function // get_allocator. These obtain the completion handler's associated // allocator, and default to std::allocator<void> if the completion // handler does not have its own. using allocator_type = boost::asio::associated_allocator_t< typename std::decay<CompletionHandler>::type, std::allocator<void>>; allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator( handler_, std::allocator<void>{}); } }; // Initiate the underlying async_write operation using our intermediate // completion handler. auto encoded_message_buffer = boost::asio::buffer(*encoded_message); boost::asio::async_write(socket, encoded_message_buffer, intermediate_completion_handler{socket, std::move(encoded_message), std::forward<CompletionHandler>(completion_handler)}); } }; template <typename T, typename CompletionToken> auto async_write_message(tcp::socket& socket, const T& message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is always // void. In this example, when the completion token is boost::asio::yield_context // (used for stackful coroutines) the return type would also be void, as // there is no non-error argument to the completion handler. When the // completion token is boost::asio::use_future it would be std::future<void>. When // the completion token is boost::asio::deferred, the return type differs for each // asynchronous operation. // // In C++11 we deduce the type from the call to boost::asio::async_initiate. -> decltype( boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), std::declval<std::unique_ptr<std::string>>())) { // Encode the message and copy it into an allocated buffer. The buffer will // be maintained for the lifetime of the asynchronous operation. std::ostringstream os; os << message; std::unique_ptr<std::string> encoded_message(new std::string(os.str())); // The boost::asio::async_initiate function takes: // // - our initiation function object, // - the completion token, // - the completion handler signature, and // - any additional arguments we need to initiate the operation. // // It then asks the completion token to create a completion handler (i.e. a // callback) with the specified signature, and invoke the initiation function // object with this completion handler as well as the additional arguments. // The return value of async_initiate is the result of our operation's // initiating function. // // Note that we wrap non-const reference arguments in std::reference_wrapper // to prevent incorrect decay-copies of these objects. return boost::asio::async_initiate< CompletionToken, void(boost::system::error_code)>( async_write_message_initiation(), token, std::ref(socket), std::move(encoded_message)); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, 123456, [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, std::string("abcdef"), boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error) { if (!error) { std::cout << "Message sent\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<void> f = async_write_message( socket, 654.321, boost::asio::use_future); io_context.run(); try { // Get the result of the operation. f.get(); std::cout << "Message sent\n"; } catch (const std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/operations/composed_1.cpp
// // composed_1.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/deferred.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/write.hpp> #include <cstring> #include <iostream> #include <string> #include <type_traits> #include <utility> using boost::asio::ip::tcp; //------------------------------------------------------------------------------ // This is the simplest example of a composed asynchronous operation, where we // simply repackage an existing operation. The asynchronous operation // requirements are met by delegating responsibility to the underlying // operation. template <typename CompletionToken> auto async_write_message(tcp::socket& socket, const char* message, CompletionToken&& token) // The return type of the initiating function is deduced from the combination // of: // // - the CompletionToken type, // - the completion handler signature, and // - the asynchronous operation's initiation function object. // // When the completion token is a simple callback, the return type is void. // However, when the completion token is boost::asio::yield_context (used for // stackful coroutines) the return type would be std::size_t, and when the // completion token is boost::asio::use_future it would be std::future<std::size_t>. // When the completion token is boost::asio::deferred, the return type differs for // each asynchronous operation. // // In this example we are trivially delegating to an underlying asynchronous // operation, so we can deduce the return type from that. -> decltype( boost::asio::async_write(socket, boost::asio::buffer(message, std::strlen(message)), std::forward<CompletionToken>(token))) { // When delegating to the underlying operation we must take care to perfectly // forward the completion token. This ensures that our operation works // correctly with move-only function objects as callbacks, as well as other // completion token types. return boost::asio::async_write(socket, boost::asio::buffer(message, std::strlen(message)), std::forward<CompletionToken>(token)); } //------------------------------------------------------------------------------ void test_callback() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using a lambda as a callback. async_write_message(socket, "Testing callback\r\n", [](const boost::system::error_code& error, std::size_t n) { if (!error) { std::cout << n << " bytes transferred\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_deferred() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the deferred completion token. This // token causes the operation's initiating function to package up the // operation and its arguments to return a function object, which may then be // used to launch the asynchronous operation. auto op = async_write_message(socket, "Testing deferred\r\n", boost::asio::deferred); // Launch the operation using a lambda as a callback. std::move(op)( [](const boost::system::error_code& error, std::size_t n) { if (!error) { std::cout << n << " bytes transferred\n"; } else { std::cout << "Error: " << error.message() << "\n"; } }); io_context.run(); } //------------------------------------------------------------------------------ void test_future() { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); tcp::socket socket = acceptor.accept(); // Test our asynchronous operation using the use_future completion token. // This token causes the operation's initiating function to return a future, // which may be used to synchronously wait for the result of the operation. std::future<std::size_t> f = async_write_message( socket, "Testing future\r\n", boost::asio::use_future); io_context.run(); try { // Get the result of the operation. std::size_t n = f.get(); std::cout << n << " bytes transferred\n"; } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } } //------------------------------------------------------------------------------ int main() { test_callback(); test_deferred(); test_future(); }
cpp
asio
data/projects/asio/example/cpp11/parallel_group/wait_for_one_error.cpp
// // wait_for_one_error.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/deferred.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( in.async_read_some( boost::asio::buffer(data), boost::asio::deferred), timer.async_wait( boost::asio::deferred) ).async_wait( boost::asio::experimental::wait_for_one_error(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp11/parallel_group/wait_for_one_success.cpp
// // wait_for_one_error.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/deferred.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( in.async_read_some( boost::asio::buffer(data), boost::asio::deferred), timer.async_wait( boost::asio::deferred) ).async_wait( boost::asio::experimental::wait_for_one_success(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp11/parallel_group/wait_for_all.cpp
// // wait_for_all.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/deferred.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( in.async_read_some( boost::asio::buffer(data), boost::asio::deferred), timer.async_wait( boost::asio::deferred) ).async_wait( boost::asio::experimental::wait_for_all(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp11/parallel_group/wait_for_one.cpp
// // wait_for_one.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/deferred.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; boost::asio::experimental::make_parallel_group( in.async_read_some( boost::asio::buffer(data), boost::asio::deferred), timer.async_wait( boost::asio::deferred) ).async_wait( boost::asio::experimental::wait_for_one(), []( std::array<std::size_t, 2> completion_order, boost::system::error_code ec1, std::size_t n1, boost::system::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp11/parallel_group/ranged_wait_for_all.cpp
// // ranged_wait_for_all.cpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <boost/asio/experimental/parallel_group.hpp> #include <iostream> #include <vector> #ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR int main() { boost::asio::io_context ctx; boost::asio::posix::stream_descriptor out(ctx, ::dup(STDOUT_FILENO)); boost::asio::posix::stream_descriptor err(ctx, ::dup(STDERR_FILENO)); using op_type = decltype( out.async_write_some( boost::asio::buffer("", 0), boost::asio::deferred ) ); std::vector<op_type> ops; ops.push_back( out.async_write_some( boost::asio::buffer("first\r\n", 7), boost::asio::deferred ) ); ops.push_back( err.async_write_some( boost::asio::buffer("second\r\n", 8), boost::asio::deferred ) ); boost::asio::experimental::make_parallel_group(ops).async_wait( boost::asio::experimental::wait_for_all(), []( std::vector<std::size_t> completion_order, std::vector<boost::system::error_code> ec, std::vector<std::size_t> n ) { for (std::size_t i = 0; i < completion_order.size(); ++i) { std::size_t idx = completion_order[i]; std::cout << "operation " << idx << " finished: "; std::cout << ec[idx] << ", " << n[idx] << "\n"; } } ); ctx.run(); } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp11/multicast/sender.cpp
// // sender.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <sstream> #include <string> #include <boost/asio.hpp> constexpr short multicast_port = 30001; constexpr int max_message_count = 10; class sender { public: sender(boost::asio::io_context& io_context, const boost::asio::ip::address& multicast_address) : endpoint_(multicast_address, multicast_port), socket_(io_context, endpoint_.protocol()), timer_(io_context), message_count_(0) { do_send(); } private: void do_send() { std::ostringstream os; os << "Message " << message_count_++; message_ = os.str(); socket_.async_send_to( boost::asio::buffer(message_), endpoint_, [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec && message_count_ < max_message_count) do_timeout(); }); } void do_timeout() { timer_.expires_after(std::chrono::seconds(1)); timer_.async_wait( [this](boost::system::error_code ec) { if (!ec) do_send(); }); } private: boost::asio::ip::udp::endpoint endpoint_; boost::asio::ip::udp::socket socket_; boost::asio::steady_timer timer_; int message_count_; std::string message_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: sender <multicast_address>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " sender 239.255.0.1\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " sender ff31::8000:1234\n"; return 1; } boost::asio::io_context io_context; sender s(io_context, boost::asio::ip::make_address(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/multicast/receiver.cpp
// // receiver.cpp // ~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <iostream> #include <string> #include <boost/asio.hpp> constexpr short multicast_port = 30001; class receiver { public: receiver(boost::asio::io_context& io_context, const boost::asio::ip::address& listen_address, const boost::asio::ip::address& multicast_address) : socket_(io_context) { // Create the socket so that multiple may be bound to the same address. boost::asio::ip::udp::endpoint listen_endpoint( listen_address, multicast_port); socket_.open(listen_endpoint.protocol()); socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true)); socket_.bind(listen_endpoint); // Join the multicast group. socket_.set_option( boost::asio::ip::multicast::join_group(multicast_address)); do_receive(); } private: void do_receive() { socket_.async_receive_from( boost::asio::buffer(data_), sender_endpoint_, [this](boost::system::error_code ec, std::size_t length) { if (!ec) { std::cout.write(data_.data(), length); std::cout << std::endl; do_receive(); } }); } boost::asio::ip::udp::socket socket_; boost::asio::ip::udp::endpoint sender_endpoint_; std::array<char, 1024> data_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: receiver <listen_address> <multicast_address>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 239.255.0.1\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 ff31::8000:1234\n"; return 1; } boost::asio::io_context io_context; receiver r(io_context, boost::asio::ip::make_address(argv[1]), boost::asio::ip::make_address(argv[2])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/executors/bank_account_1.cpp
#include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <iostream> using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // Traditional active object pattern. // Member functions do not block. class bank_account { int balance_ = 0; mutable static_thread_pool pool_{1}; public: void deposit(int amount) { pool_.executor().execute( [this, amount] { balance_ += amount; }); } void withdraw(int amount) { pool_.executor().execute( [this, amount] { if (balance_ >= amount) balance_ -= amount; }); } void print_balance() const { pool_.executor().execute( [this] { std::cout << "balance = " << balance_ << "\n"; }); } ~bank_account() { pool_.wait(); } }; int main() { bank_account acct; acct.deposit(20); acct.withdraw(10); acct.print_balance(); }
cpp
asio
data/projects/asio/example/cpp11/executors/priority_scheduler.cpp
#include <boost/asio/dispatch.hpp> #include <boost/asio/execution_context.hpp> #include <condition_variable> #include <iostream> #include <memory> #include <mutex> #include <queue> using boost::asio::dispatch; using boost::asio::execution_context; namespace execution = boost::asio::execution; class priority_scheduler : public execution_context { public: // A class that satisfies the Executor requirements. class executor_type { public: executor_type(priority_scheduler& ctx, int pri) noexcept : context_(ctx), priority_(pri) { } priority_scheduler& query(execution::context_t) const noexcept { return context_; } template <class Func> void execute(Func f) const { auto p(std::make_shared<item<Func>>(priority_, std::move(f))); std::lock_guard<std::mutex> lock(context_.mutex_); context_.queue_.push(p); context_.condition_.notify_one(); } friend bool operator==(const executor_type& a, const executor_type& b) noexcept { return &a.context_ == &b.context_; } friend bool operator!=(const executor_type& a, const executor_type& b) noexcept { return &a.context_ != &b.context_; } private: priority_scheduler& context_; int priority_; }; ~priority_scheduler() noexcept { shutdown(); destroy(); } executor_type get_executor(int pri = 0) noexcept { return executor_type(*const_cast<priority_scheduler*>(this), pri); } void run() { std::unique_lock<std::mutex> lock(mutex_); for (;;) { condition_.wait(lock, [&]{ return stopped_ || !queue_.empty(); }); if (stopped_) return; auto p(queue_.top()); queue_.pop(); lock.unlock(); p->execute_(p); lock.lock(); } } void stop() { std::lock_guard<std::mutex> lock(mutex_); stopped_ = true; condition_.notify_all(); } private: struct item_base { int priority_; void (*execute_)(std::shared_ptr<item_base>&); }; template <class Func> struct item : item_base { item(int pri, Func f) : function_(std::move(f)) { priority_ = pri; execute_ = [](std::shared_ptr<item_base>& p) { Func tmp(std::move(static_cast<item*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; struct item_comp { bool operator()( const std::shared_ptr<item_base>& a, const std::shared_ptr<item_base>& b) { return a->priority_ < b->priority_; } }; std::mutex mutex_; std::condition_variable condition_; std::priority_queue< std::shared_ptr<item_base>, std::vector<std::shared_ptr<item_base>>, item_comp> queue_; bool stopped_ = false; }; int main() { priority_scheduler sched; auto low = sched.get_executor(0); auto med = sched.get_executor(1); auto high = sched.get_executor(2); dispatch(low, []{ std::cout << "1\n"; }); dispatch(low, []{ std::cout << "11\n"; }); dispatch(med, []{ std::cout << "2\n"; }); dispatch(med, []{ std::cout << "22\n"; }); dispatch(high, []{ std::cout << "3\n"; }); dispatch(high, []{ std::cout << "33\n"; }); dispatch(high, []{ std::cout << "333\n"; }); dispatch(sched.get_executor(-1), [&]{ sched.stop(); }); sched.run(); }
cpp
asio
data/projects/asio/example/cpp11/executors/fork_join.cpp
#include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <algorithm> #include <condition_variable> #include <memory> #include <mutex> #include <queue> #include <thread> #include <numeric> using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // A fixed-size thread pool used to implement fork/join semantics. Functions // are scheduled using a simple FIFO queue. Implementing work stealing, or // using a queue based on atomic operations, are left as tasks for the reader. class fork_join_pool { public: // The constructor starts a thread pool with the specified number of threads. // Note that the thread_count is not a fixed limit on the pool's concurrency. // Additional threads may temporarily be added to the pool if they join a // fork_executor. explicit fork_join_pool( std::size_t thread_count = std::max(std::thread::hardware_concurrency(), 1u) * 2) : use_count_(1), threads_(thread_count) { try { // Ask each thread in the pool to dequeue and execute functions until // it is time to shut down, i.e. the use count is zero. for (thread_count_ = 0; thread_count_ < thread_count; ++thread_count_) { threads_.executor().execute( [this] { std::unique_lock<std::mutex> lock(mutex_); while (use_count_ > 0) if (!execute_next(lock)) condition_.wait(lock); }); } } catch (...) { stop_threads(); threads_.wait(); throw; } } // The destructor waits for the pool to finish executing functions. ~fork_join_pool() { stop_threads(); threads_.wait(); } private: friend class fork_executor; // The base for all functions that are queued in the pool. struct function_base { std::shared_ptr<std::size_t> work_count_; void (*execute_)(std::shared_ptr<function_base>& p); }; // Execute the next function from the queue, if any. Returns true if a // function was executed, and false if the queue was empty. bool execute_next(std::unique_lock<std::mutex>& lock) { if (queue_.empty()) return false; auto p(queue_.front()); queue_.pop(); lock.unlock(); execute(lock, p); return true; } // Execute a function and decrement the outstanding work. void execute(std::unique_lock<std::mutex>& lock, std::shared_ptr<function_base>& p) { std::shared_ptr<std::size_t> work_count(std::move(p->work_count_)); try { p->execute_(p); lock.lock(); do_work_finished(work_count); } catch (...) { lock.lock(); do_work_finished(work_count); throw; } } // Increment outstanding work. void do_work_started(const std::shared_ptr<std::size_t>& work_count) noexcept { if (++(*work_count) == 1) ++use_count_; } // Decrement outstanding work. Notify waiting threads if we run out. void do_work_finished(const std::shared_ptr<std::size_t>& work_count) noexcept { if (--(*work_count) == 0) { --use_count_; condition_.notify_all(); } } // Dispatch a function, executing it immediately if the queue is already // loaded. Otherwise adds the function to the queue and wakes a thread. void do_execute(std::shared_ptr<function_base> p, const std::shared_ptr<std::size_t>& work_count) { std::unique_lock<std::mutex> lock(mutex_); if (queue_.size() > thread_count_ * 16) { do_work_started(work_count); lock.unlock(); execute(lock, p); } else { queue_.push(p); do_work_started(work_count); condition_.notify_one(); } } // Ask all threads to shut down. void stop_threads() { std::lock_guard<std::mutex> lock(mutex_); --use_count_; condition_.notify_all(); } std::mutex mutex_; std::condition_variable condition_; std::queue<std::shared_ptr<function_base>> queue_; std::size_t use_count_; std::size_t thread_count_; static_thread_pool threads_; }; // A class that satisfies the Executor requirements. Every function or piece of // work associated with a fork_executor is part of a single, joinable group. class fork_executor { public: fork_executor(fork_join_pool& ctx) : context_(ctx), work_count_(std::make_shared<std::size_t>(0)) { } fork_join_pool& query(execution::context_t) const noexcept { return context_; } template <class Func> void execute(Func f) const { auto p(std::make_shared<function<Func>>(std::move(f), work_count_)); context_.do_execute(p, work_count_); } friend bool operator==(const fork_executor& a, const fork_executor& b) noexcept { return a.work_count_ == b.work_count_; } friend bool operator!=(const fork_executor& a, const fork_executor& b) noexcept { return a.work_count_ != b.work_count_; } // Block until all work associated with the executor is complete. While it is // waiting, the thread may be borrowed to execute functions from the queue. void join() const { std::unique_lock<std::mutex> lock(context_.mutex_); while (*work_count_ > 0) if (!context_.execute_next(lock)) context_.condition_.wait(lock); } private: template <class Func> struct function : fork_join_pool::function_base { explicit function(Func f, const std::shared_ptr<std::size_t>& w) : function_(std::move(f)) { work_count_ = w; execute_ = [](std::shared_ptr<fork_join_pool::function_base>& p) { Func tmp(std::move(static_cast<function*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; fork_join_pool& context_; std::shared_ptr<std::size_t> work_count_; }; // Helper class to automatically join a fork_executor when exiting a scope. class join_guard { public: explicit join_guard(const fork_executor& ex) : ex_(ex) {} join_guard(const join_guard&) = delete; join_guard(join_guard&&) = delete; ~join_guard() { ex_.join(); } private: fork_executor ex_; }; //------------------------------------------------------------------------------ #include <algorithm> #include <iostream> #include <random> #include <vector> fork_join_pool pool; template <class Iterator> void fork_join_sort(Iterator begin, Iterator end) { std::size_t n = end - begin; if (n > 32768) { { fork_executor fork(pool); join_guard join(fork); fork.execute([=]{ fork_join_sort(begin, begin + n / 2); }); fork.execute([=]{ fork_join_sort(begin + n / 2, end); }); } std::inplace_merge(begin, begin + n / 2, end); } else { std::sort(begin, end); } } int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: fork_join <size>\n"; return 1; } std::vector<double> vec(std::atoll(argv[1])); std::iota(vec.begin(), vec.end(), 0); std::random_device rd; std::mt19937 g(rd()); std::shuffle(vec.begin(), vec.end(), g); std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); fork_join_sort(vec.begin(), vec.end()); std::chrono::steady_clock::duration elapsed = std::chrono::steady_clock::now() - start; std::cout << "sort took "; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); std::cout << " microseconds" << std::endl; }
cpp
asio
data/projects/asio/example/cpp11/executors/pipeline.cpp
#include <boost/asio/associated_executor.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/post.hpp> #include <boost/asio/system_executor.hpp> #include <boost/asio/use_future.hpp> #include <condition_variable> #include <future> #include <memory> #include <mutex> #include <queue> #include <thread> #include <vector> #include <cctype> using boost::asio::execution_context; using boost::asio::executor_binder; using boost::asio::get_associated_executor; using boost::asio::post; using boost::asio::system_executor; using boost::asio::use_future; using boost::asio::use_service; namespace execution = boost::asio::execution; // An executor that launches a new thread for each function submitted to it. // This class satisfies the executor requirements. class thread_executor { private: // Service to track all threads started through a thread_executor. class thread_bag : public execution_context::service { public: typedef thread_bag key_type; explicit thread_bag(execution_context& ctx) : execution_context::service(ctx) { } void add_thread(std::thread&& t) { std::unique_lock<std::mutex> lock(mutex_); threads_.push_back(std::move(t)); } private: virtual void shutdown() { for (auto& t : threads_) t.join(); } std::mutex mutex_; std::vector<std::thread> threads_; }; public: execution_context& query(execution::context_t) const { return boost::asio::query(system_executor(), execution::context); } execution::blocking_t query(execution::blocking_t) const { return execution::blocking.never; } thread_executor require(execution::blocking_t::never_t) const { return *this; } template <class Func> void execute(Func f) const { thread_bag& bag = use_service<thread_bag>(query(execution::context)); bag.add_thread(std::thread(std::move(f))); } friend bool operator==(const thread_executor&, const thread_executor&) noexcept { return true; } friend bool operator!=(const thread_executor&, const thread_executor&) noexcept { return false; } }; // Base class for all thread-safe queue implementations. class queue_impl_base { template <class> friend class queue_front; template <class> friend class queue_back; std::mutex mutex_; std::condition_variable condition_; bool stop_ = false; }; // Underlying implementation of a thread-safe queue, shared between the // queue_front and queue_back classes. template <class T> class queue_impl : public queue_impl_base { template <class> friend class queue_front; template <class> friend class queue_back; std::queue<T> queue_; }; // The front end of a queue between consecutive pipeline stages. template <class T> class queue_front { public: typedef T value_type; explicit queue_front(std::shared_ptr<queue_impl<T>> impl) : impl_(impl) { } void push(T t) { std::unique_lock<std::mutex> lock(impl_->mutex_); impl_->queue_.push(std::move(t)); impl_->condition_.notify_one(); } void stop() { std::unique_lock<std::mutex> lock(impl_->mutex_); impl_->stop_ = true; impl_->condition_.notify_one(); } private: std::shared_ptr<queue_impl<T>> impl_; }; // The back end of a queue between consecutive pipeline stages. template <class T> class queue_back { public: typedef T value_type; explicit queue_back(std::shared_ptr<queue_impl<T>> impl) : impl_(impl) { } bool pop(T& t) { std::unique_lock<std::mutex> lock(impl_->mutex_); while (impl_->queue_.empty() && !impl_->stop_) impl_->condition_.wait(lock); if (!impl_->queue_.empty()) { t = impl_->queue_.front(); impl_->queue_.pop(); return true; } return false; } private: std::shared_ptr<queue_impl<T>> impl_; }; // Launch the last stage in a pipeline. template <class T, class F> std::future<void> pipeline(queue_back<T> in, F f) { // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function, and as we're the last stage return a future so that the // caller can wait for the pipeline to finish. return post(ex, use_future([in, f]() mutable { f(in); })); } // Launch an intermediate stage in a pipeline. template <class T, class F, class... Tail> std::future<void> pipeline(queue_back<T> in, F f, Tail... t) { // Determine the output queue type. typedef typename executor_binder<F, thread_executor>::second_argument_type::value_type output_value_type; // Create the output queue and its implementation. auto out_impl = std::make_shared<queue_impl<output_value_type>>(); queue_front<output_value_type> out(out_impl); queue_back<output_value_type> next_in(out_impl); // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function. post(ex, [in, out, f]() mutable { f(in, out); out.stop(); }); // Launch the rest of the pipeline. return pipeline(next_in, std::move(t)...); } // Launch the first stage in a pipeline. template <class F, class... Tail> std::future<void> pipeline(F f, Tail... t) { // Determine the output queue type. typedef typename executor_binder<F, thread_executor>::argument_type::value_type output_value_type; // Create the output queue and its implementation. auto out_impl = std::make_shared<queue_impl<output_value_type>>(); queue_front<output_value_type> out(out_impl); queue_back<output_value_type> next_in(out_impl); // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function. post(ex, [out, f]() mutable { f(out); out.stop(); }); // Launch the rest of the pipeline. return pipeline(next_in, std::move(t)...); } //------------------------------------------------------------------------------ #include <boost/asio/thread_pool.hpp> #include <iostream> #include <string> using boost::asio::bind_executor; using boost::asio::thread_pool; void reader(queue_front<std::string> out) { std::string line; while (std::getline(std::cin, line)) out.push(line); } void filter(queue_back<std::string> in, queue_front<std::string> out) { std::string line; while (in.pop(line)) if (line.length() > 5) out.push(line); } void upper(queue_back<std::string> in, queue_front<std::string> out) { std::string line; while (in.pop(line)) { std::string new_line; for (char c : line) new_line.push_back(std::toupper(c)); out.push(new_line); } } void writer(queue_back<std::string> in) { std::size_t count = 0; std::string line; while (in.pop(line)) std::cout << count++ << ": " << line << std::endl; } int main() { thread_pool pool(1); auto f = pipeline(reader, filter, bind_executor(pool, upper), writer); f.wait(); }
cpp
asio
data/projects/asio/example/cpp11/executors/actor.cpp
#include <boost/asio/any_io_executor.hpp> #include <boost/asio/defer.hpp> #include <boost/asio/post.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/system_executor.hpp> #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <typeinfo> #include <vector> using boost::asio::any_io_executor; using boost::asio::defer; using boost::asio::post; using boost::asio::strand; using boost::asio::system_executor; //------------------------------------------------------------------------------ // A tiny actor framework // ~~~~~~~~~~~~~~~~~~~~~~ class actor; // Used to identify the sender and recipient of messages. typedef actor* actor_address; // Base class for all registered message handlers. class message_handler_base { public: virtual ~message_handler_base() {} // Used to determine which message handlers receive an incoming message. virtual const std::type_info& message_id() const = 0; }; // Base class for a handler for a specific message type. template <class Message> class message_handler : public message_handler_base { public: // Handle an incoming message. virtual void handle_message(Message msg, actor_address from) = 0; }; // Concrete message handler for a specific message type. template <class Actor, class Message> class mf_message_handler : public message_handler<Message> { public: // Construct a message handler to invoke the specified member function. mf_message_handler(void (Actor::* mf)(Message, actor_address), Actor* a) : function_(mf), actor_(a) { } // Used to determine which message handlers receive an incoming message. virtual const std::type_info& message_id() const { return typeid(Message); } // Handle an incoming message. virtual void handle_message(Message msg, actor_address from) { (actor_->*function_)(std::move(msg), from); } // Determine whether the message handler represents the specified function. bool is_function(void (Actor::* mf)(Message, actor_address)) const { return mf == function_; } private: void (Actor::* function_)(Message, actor_address); Actor* actor_; }; // Base class for all actors. class actor { public: virtual ~actor() { } // Obtain the actor's address for use as a message sender or recipient. actor_address address() { return this; } // Send a message from one actor to another. template <class Message> friend void send(Message msg, actor_address from, actor_address to) { // Execute the message handler in the context of the target's executor. post(to->executor_, [=] { to->call_handler(std::move(msg), from); }); } protected: // Construct the actor to use the specified executor for all message handlers. actor(any_io_executor e) : executor_(std::move(e)) { } // Register a handler for a specific message type. Duplicates are permitted. template <class Actor, class Message> void register_handler(void (Actor::* mf)(Message, actor_address)) { handlers_.push_back( std::make_shared<mf_message_handler<Actor, Message>>( mf, static_cast<Actor*>(this))); } // Deregister a handler. Removes only the first matching handler. template <class Actor, class Message> void deregister_handler(void (Actor::* mf)(Message, actor_address)) { const std::type_info& id = typeid(Message); for (auto iter = handlers_.begin(); iter != handlers_.end(); ++iter) { if ((*iter)->message_id() == id) { auto mh = static_cast<mf_message_handler<Actor, Message>*>(iter->get()); if (mh->is_function(mf)) { handlers_.erase(iter); return; } } } } // Send a message from within a message handler. template <class Message> void tail_send(Message msg, actor_address to) { // Execute the message handler in the context of the target's executor. actor* from = this; defer(to->executor_, [=] { to->call_handler(std::move(msg), from); }); } private: // Find the matching message handlers, if any, and call them. template <class Message> void call_handler(Message msg, actor_address from) { const std::type_info& message_id = typeid(Message); for (auto& h: handlers_) { if (h->message_id() == message_id) { auto mh = static_cast<message_handler<Message>*>(h.get()); mh->handle_message(msg, from); } } } // All messages associated with a single actor object should be processed // non-concurrently. We use a strand to ensure non-concurrent execution even // if the underlying executor may use multiple threads. strand<any_io_executor> executor_; std::vector<std::shared_ptr<message_handler_base>> handlers_; }; // A concrete actor that allows synchronous message retrieval. template <class Message> class receiver : public actor { public: receiver() : actor(system_executor()) { register_handler(&receiver::message_handler); } // Block until a message has been received. Message wait() { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [this]{ return !message_queue_.empty(); }); Message msg(std::move(message_queue_.front())); message_queue_.pop_front(); return msg; } private: // Handle a new message by adding it to the queue and waking a waiter. void message_handler(Message msg, actor_address /* from */) { std::lock_guard<std::mutex> lock(mutex_); message_queue_.push_back(std::move(msg)); condition_.notify_one(); } std::mutex mutex_; std::condition_variable condition_; std::deque<Message> message_queue_; }; //------------------------------------------------------------------------------ #include <boost/asio/thread_pool.hpp> #include <iostream> using boost::asio::thread_pool; class member : public actor { public: explicit member(any_io_executor e) : actor(std::move(e)) { register_handler(&member::init_handler); } private: void init_handler(actor_address next, actor_address from) { next_ = next; caller_ = from; register_handler(&member::token_handler); deregister_handler(&member::init_handler); } void token_handler(int token, actor_address /*from*/) { int msg(token); actor_address to(caller_); if (token > 0) { msg = token - 1; to = next_; } tail_send(msg, to); } actor_address next_; actor_address caller_; }; int main() { const std::size_t num_threads = 16; const int num_hops = 50000000; const std::size_t num_actors = 503; const int token_value = (num_hops + num_actors - 1) / num_actors; const std::size_t actors_per_thread = num_actors / num_threads; struct single_thread_pool : thread_pool { single_thread_pool() : thread_pool(1) {} }; single_thread_pool pools[num_threads]; std::vector<std::shared_ptr<member>> members(num_actors); receiver<int> rcvr; // Create the member actors. for (std::size_t i = 0; i < num_actors; ++i) members[i] = std::make_shared<member>(pools[(i / actors_per_thread) % num_threads].get_executor()); // Initialise the actors by passing each one the address of the next actor in the ring. for (std::size_t i = num_actors, next_i = 0; i > 0; next_i = --i) send(members[next_i]->address(), rcvr.address(), members[i - 1]->address()); // Send exactly one token to each actor, all with the same initial value, rounding up if required. for (std::size_t i = 0; i < num_actors; ++i) send(token_value, rcvr.address(), members[i]->address()); // Wait for all signal messages, indicating the tokens have all reached zero. for (std::size_t i = 0; i < num_actors; ++i) rcvr.wait(); }
cpp
asio
data/projects/asio/example/cpp11/executors/bank_account_2.cpp
#include <boost/asio/execution.hpp> #include <boost/asio/static_thread_pool.hpp> #include <iostream> using boost::asio::static_thread_pool; namespace execution = boost::asio::execution; // Traditional active object pattern. // Member functions block until operation is finished. class bank_account { int balance_ = 0; mutable static_thread_pool pool_{1}; public: void deposit(int amount) { boost::asio::require(pool_.executor(), execution::blocking.always).execute( [this, amount] { balance_ += amount; }); } void withdraw(int amount) { boost::asio::require(pool_.executor(), execution::blocking.always).execute( [this, amount] { if (balance_ >= amount) balance_ -= amount; }); } int balance() const { int result = 0; boost::asio::require(pool_.executor(), execution::blocking.always).execute( [this, &result] { result = balance_; }); return result; } }; int main() { bank_account acct; acct.deposit(20); acct.withdraw(10); std::cout << "balance = " << acct.balance() << "\n"; }
cpp
asio
data/projects/asio/example/cpp11/chat/posix_chat_client.cpp
// // posix_chat_client.cpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <cstdlib> #include <cstring> #include <iostream> #include <boost/asio.hpp> #include "chat_message.hpp" #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) using boost::asio::ip::tcp; namespace posix = boost::asio::posix; class posix_chat_client { public: posix_chat_client(boost::asio::io_context& io_context, const tcp::resolver::results_type& endpoints) : socket_(io_context), input_(io_context, ::dup(STDIN_FILENO)), output_(io_context, ::dup(STDOUT_FILENO)), input_buffer_(chat_message::max_body_length) { do_connect(endpoints); } private: void do_connect(const tcp::resolver::results_type& endpoints) { boost::asio::async_connect(socket_, endpoints, [this](boost::system::error_code ec, tcp::endpoint) { if (!ec) { do_read_header(); do_read_input(); } }); } void do_read_header() { boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { close(); } }); } void do_read_body() { boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { do_write_output(); } else { close(); } }); } void do_write_output() { // Write out the message we just received, terminated by a newline. static char eol[] = { '\n' }; std::array<boost::asio::const_buffer, 2> buffers = {{ boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), boost::asio::buffer(eol) }}; boost::asio::async_write(output_, buffers, [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { do_read_header(); } else { close(); } }); } void do_read_input() { // Read a line of input entered by the user. boost::asio::async_read_until(input_, input_buffer_, '\n', [this](boost::system::error_code ec, std::size_t length) { if (!ec) { // Write the message (minus the newline) to the server. write_msg_.body_length(length - 1); input_buffer_.sgetn(write_msg_.body(), length - 1); input_buffer_.consume(1); // Remove newline from input. write_msg_.encode_header(); do_write_message(); } else if (ec == boost::asio::error::not_found) { // Didn't get a newline. Send whatever we have. write_msg_.body_length(input_buffer_.size()); input_buffer_.sgetn(write_msg_.body(), input_buffer_.size()); write_msg_.encode_header(); do_write_message(); } else { close(); } }); } void do_write_message() { boost::asio::async_write(socket_, boost::asio::buffer(write_msg_.data(), write_msg_.length()), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { do_read_input(); } else { close(); } }); } void close() { // Cancel all outstanding asynchronous operations. socket_.close(); input_.close(); output_.close(); } private: tcp::socket socket_; posix::stream_descriptor input_; posix::stream_descriptor output_; chat_message read_msg_; chat_message write_msg_; boost::asio::streambuf input_buffer_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: posix_chat_client <host> <port>\n"; return 1; } boost::asio::io_context io_context; tcp::resolver resolver(io_context); tcp::resolver::results_type endpoints = resolver.resolve(argv[1], argv[2]); posix_chat_client c(io_context, endpoints); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
cpp
asio
data/projects/asio/example/cpp11/chat/chat_server.cpp
// // chat_server.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <deque> #include <iostream> #include <list> #include <memory> #include <set> #include <utility> #include <boost/asio.hpp> #include "chat_message.hpp" using boost::asio::ip::tcp; //---------------------------------------------------------------------- typedef std::deque<chat_message> chat_message_queue; //---------------------------------------------------------------------- class chat_participant { public: virtual ~chat_participant() {} virtual void deliver(const chat_message& msg) = 0; }; typedef std::shared_ptr<chat_participant> chat_participant_ptr; //---------------------------------------------------------------------- class chat_room { public: void join(chat_participant_ptr participant) { participants_.insert(participant); for (auto msg: recent_msgs_) participant->deliver(msg); } void leave(chat_participant_ptr participant) { participants_.erase(participant); } void deliver(const chat_message& msg) { recent_msgs_.push_back(msg); while (recent_msgs_.size() > max_recent_msgs) recent_msgs_.pop_front(); for (auto participant: participants_) participant->deliver(msg); } private: std::set<chat_participant_ptr> participants_; enum { max_recent_msgs = 100 }; chat_message_queue recent_msgs_; }; //---------------------------------------------------------------------- class chat_session : public chat_participant, public std::enable_shared_from_this<chat_session> { public: chat_session(tcp::socket socket, chat_room& room) : socket_(std::move(socket)), room_(room) { } void start() { room_.join(shared_from_this()); do_read_header(); } void deliver(const chat_message& msg) { bool write_in_progress = !write_msgs_.empty(); write_msgs_.push_back(msg); if (!write_in_progress) { do_write(); } } private: void do_read_header() { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { room_.leave(shared_from_this()); } }); } void do_read_body() { auto self(shared_from_this()); boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { room_.deliver(read_msg_); do_read_header(); } else { room_.leave(shared_from_this()); } }); } void do_write() { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { write_msgs_.pop_front(); if (!write_msgs_.empty()) { do_write(); } } else { room_.leave(shared_from_this()); } }); } tcp::socket socket_; chat_room& room_; chat_message read_msg_; chat_message_queue write_msgs_; }; //---------------------------------------------------------------------- class chat_server { public: chat_server(boost::asio::io_context& io_context, const tcp::endpoint& endpoint) : acceptor_(io_context, endpoint) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](boost::system::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<chat_session>(std::move(socket), room_)->start(); } do_accept(); }); } tcp::acceptor acceptor_; chat_room room_; }; //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc < 2) { std::cerr << "Usage: chat_server <port> [<port> ...]\n"; return 1; } boost::asio::io_context io_context; std::list<chat_server> servers; for (int i = 1; i < argc; ++i) { tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[i])); servers.emplace_back(io_context, endpoint); } io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/chat/chat_message.hpp
// // chat_message.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef CHAT_MESSAGE_HPP #define CHAT_MESSAGE_HPP #include <cstdio> #include <cstdlib> #include <cstring> class chat_message { public: static constexpr std::size_t header_length = 4; static constexpr std::size_t max_body_length = 512; chat_message() : body_length_(0) { } const char* data() const { return data_; } char* data() { return data_; } std::size_t length() const { return header_length + body_length_; } const char* body() const { return data_ + header_length; } char* body() { return data_ + header_length; } std::size_t body_length() const { return body_length_; } void body_length(std::size_t new_length) { body_length_ = new_length; if (body_length_ > max_body_length) body_length_ = max_body_length; } bool decode_header() { char header[header_length + 1] = ""; std::strncat(header, data_, header_length); body_length_ = std::atoi(header); if (body_length_ > max_body_length) { body_length_ = 0; return false; } return true; } void encode_header() { char header[header_length + 1] = ""; std::sprintf(header, "%4d", static_cast<int>(body_length_)); std::memcpy(data_, header, header_length); } private: char data_[header_length + max_body_length]; std::size_t body_length_; }; #endif // CHAT_MESSAGE_HPP
hpp
asio
data/projects/asio/example/cpp11/chat/chat_client.cpp
// // chat_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <deque> #include <iostream> #include <thread> #include <boost/asio.hpp> #include "chat_message.hpp" using boost::asio::ip::tcp; typedef std::deque<chat_message> chat_message_queue; class chat_client { public: chat_client(boost::asio::io_context& io_context, const tcp::resolver::results_type& endpoints) : io_context_(io_context), socket_(io_context) { do_connect(endpoints); } void write(const chat_message& msg) { boost::asio::post(io_context_, [this, msg]() { bool write_in_progress = !write_msgs_.empty(); write_msgs_.push_back(msg); if (!write_in_progress) { do_write(); } }); } void close() { boost::asio::post(io_context_, [this]() { socket_.close(); }); } private: void do_connect(const tcp::resolver::results_type& endpoints) { boost::asio::async_connect(socket_, endpoints, [this](boost::system::error_code ec, tcp::endpoint) { if (!ec) { do_read_header(); } }); } void do_read_header() { boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { socket_.close(); } }); } void do_read_body() { boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { std::cout.write(read_msg_.body(), read_msg_.body_length()); std::cout << "\n"; do_read_header(); } else { socket_.close(); } }); } void do_write() { boost::asio::async_write(socket_, boost::asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { write_msgs_.pop_front(); if (!write_msgs_.empty()) { do_write(); } } else { socket_.close(); } }); } private: boost::asio::io_context& io_context_; tcp::socket socket_; chat_message read_msg_; chat_message_queue write_msgs_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: chat_client <host> <port>\n"; return 1; } boost::asio::io_context io_context; tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); chat_client c(io_context, endpoints); std::thread t([&io_context](){ io_context.run(); }); char line[chat_message::max_body_length + 1]; while (std::cin.getline(line, chat_message::max_body_length + 1)) { chat_message msg; msg.body_length(std::strlen(line)); std::memcpy(msg.body(), line, msg.body_length()); msg.encode_header(); c.write(msg); } c.close(); t.join(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/porthopper/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <cmath> #include <cstdlib> #include <exception> #include <functional> #include <iostream> #include <memory> #include <set> #include "protocol.hpp" using boost::asio::ip::tcp; using boost::asio::ip::udp; typedef std::shared_ptr<tcp::socket> tcp_socket_ptr; typedef std::shared_ptr<boost::asio::steady_timer> timer_ptr; typedef std::shared_ptr<control_request> control_request_ptr; class server { public: // Construct the server to wait for incoming control connections. server(boost::asio::io_context& io_context, unsigned short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)), timer_(io_context), udp_socket_(io_context, udp::endpoint(udp::v4(), 0)), next_frame_number_(1) { // Start waiting for a new control connection. tcp_socket_ptr new_socket(new tcp::socket(acceptor_.get_executor())); acceptor_.async_accept(*new_socket, std::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_socket)); // Start the timer used to generate outgoing frames. timer_.expires_after(boost::asio::chrono::milliseconds(100)); timer_.async_wait(std::bind(&server::handle_timer, this)); } // Handle a new control connection. void handle_accept(const boost::system::error_code& ec, tcp_socket_ptr socket) { if (!ec) { // Start receiving control requests on the connection. control_request_ptr request(new control_request); boost::asio::async_read(*socket, request->to_buffers(), std::bind(&server::handle_control_request, this, boost::asio::placeholders::error, socket, request)); } // Start waiting for a new control connection. tcp_socket_ptr new_socket(new tcp::socket(acceptor_.get_executor())); acceptor_.async_accept(*new_socket, std::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_socket)); } // Handle a new control request. void handle_control_request(const boost::system::error_code& ec, tcp_socket_ptr socket, control_request_ptr request) { if (!ec) { // Delay handling of the control request to simulate network latency. timer_ptr delay_timer( new boost::asio::steady_timer(acceptor_.get_executor())); delay_timer->expires_after(boost::asio::chrono::seconds(2)); delay_timer->async_wait( std::bind(&server::handle_control_request_timer, this, socket, request, delay_timer)); } } void handle_control_request_timer(tcp_socket_ptr socket, control_request_ptr request, timer_ptr /*delay_timer*/) { // Determine what address this client is connected from, since // subscriptions must be stored on the server as a complete endpoint, not // just a port. We use the non-throwing overload of remote_endpoint() since // it may fail if the socket is no longer connected. boost::system::error_code ec; tcp::endpoint remote_endpoint = socket->remote_endpoint(ec); if (!ec) { // Remove old port subscription, if any. if (unsigned short old_port = request->old_port()) { udp::endpoint old_endpoint(remote_endpoint.address(), old_port); subscribers_.erase(old_endpoint); std::cout << "Removing subscription " << old_endpoint << std::endl; } // Add new port subscription, if any. if (unsigned short new_port = request->new_port()) { udp::endpoint new_endpoint(remote_endpoint.address(), new_port); subscribers_.insert(new_endpoint); std::cout << "Adding subscription " << new_endpoint << std::endl; } } // Wait for next control request on this connection. boost::asio::async_read(*socket, request->to_buffers(), std::bind(&server::handle_control_request, this, boost::asio::placeholders::error, socket, request)); } // Every time the timer fires we will generate a new frame and send it to all // subscribers. void handle_timer() { // Generate payload. double x = next_frame_number_ * 0.2; double y = std::sin(x); int char_index = static_cast<int>((y + 1.0) * (frame::payload_size / 2)); std::string payload; for (int i = 0; i < frame::payload_size; ++i) payload += (i == char_index ? '*' : '.'); // Create the frame to be sent to all subscribers. frame f(next_frame_number_++, payload); // Send frame to all subscribers. We can use synchronous calls here since // UDP send operations typically do not block. std::set<udp::endpoint>::iterator j; for (j = subscribers_.begin(); j != subscribers_.end(); ++j) { boost::system::error_code ec; udp_socket_.send_to(f.to_buffers(), *j, 0, ec); } // Wait for next timeout. timer_.expires_after(boost::asio::chrono::milliseconds(100)); timer_.async_wait(std::bind(&server::handle_timer, this)); } private: // The acceptor used to accept incoming control connections. tcp::acceptor acceptor_; // The timer used for generating data. boost::asio::steady_timer timer_; // The socket used to send data to subscribers. udp::socket udp_socket_; // The next frame number. unsigned long next_frame_number_; // The set of endpoints that are subscribed. std::set<udp::endpoint> subscribers_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: server <port>\n"; return 1; } boost::asio::io_context io_context; using namespace std; // For atoi. server s(io_context, atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/porthopper/protocol.hpp
// // protocol.hpp // ~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef PORTHOPPER_PROTOCOL_HPP #define PORTHOPPER_PROTOCOL_HPP #include <boost/asio.hpp> #include <array> #include <cstring> #include <iomanip> #include <string> #include <strstream> // This request is sent by the client to the server over a TCP connection. // The client uses it to perform three functions: // - To request that data start being sent to a given port. // - To request that data is no longer sent to a given port. // - To change the target port to another. class control_request { public: // Construct an empty request. Used when receiving. control_request() { } // Create a request to start sending data to a given port. static const control_request start(unsigned short port) { return control_request(0, port); } // Create a request to stop sending data to a given port. static const control_request stop(unsigned short port) { return control_request(port, 0); } // Create a request to change the port that data is sent to. static const control_request change( unsigned short old_port, unsigned short new_port) { return control_request(old_port, new_port); } // Get the old port. Returns 0 for start requests. unsigned short old_port() const { std::istrstream is(data_, encoded_port_size); unsigned short port = 0; is >> std::setw(encoded_port_size) >> std::hex >> port; return port; } // Get the new port. Returns 0 for stop requests. unsigned short new_port() const { std::istrstream is(data_ + encoded_port_size, encoded_port_size); unsigned short port = 0; is >> std::setw(encoded_port_size) >> std::hex >> port; return port; } // Obtain buffers for reading from or writing to a socket. std::array<boost::asio::mutable_buffer, 1> to_buffers() { std::array<boost::asio::mutable_buffer, 1> buffers = { { boost::asio::buffer(data_) } }; return buffers; } private: // Construct with specified old and new ports. control_request(unsigned short old_port_number, unsigned short new_port_number) { std::ostrstream os(data_, control_request_size); os << std::setw(encoded_port_size) << std::hex << old_port_number; os << std::setw(encoded_port_size) << std::hex << new_port_number; } // The length in bytes of a control_request and its components. enum { encoded_port_size = 4, // 16-bit port in hex. control_request_size = encoded_port_size * 2 }; // The encoded request data. char data_[control_request_size]; }; // This frame is sent from the server to subscribed clients over UDP. class frame { public: // The maximum allowable length of the payload. enum { payload_size = 32 }; // Construct an empty frame. Used when receiving. frame() { } // Construct a frame with specified frame number and payload. frame(unsigned long frame_number, const std::string& payload_data) { std::ostrstream os(data_, frame_size); os << std::setw(encoded_number_size) << std::hex << frame_number; os << std::setw(payload_size) << std::setfill(' ') << payload_data.substr(0, payload_size); } // Get the frame number. unsigned long number() const { std::istrstream is(data_, encoded_number_size); unsigned long frame_number = 0; is >> std::setw(encoded_number_size) >> std::hex >> frame_number; return frame_number; } // Get the payload data. const std::string payload() const { return std::string(data_ + encoded_number_size, payload_size); } // Obtain buffers for reading from or writing to a socket. std::array<boost::asio::mutable_buffer, 1> to_buffers() { std::array<boost::asio::mutable_buffer, 1> buffers = { { boost::asio::buffer(data_) } }; return buffers; } private: // The length in bytes of a frame and its components. enum { encoded_number_size = 8, // Frame number in hex. frame_size = encoded_number_size + payload_size }; // The encoded frame data. char data_[frame_size]; }; #endif // PORTHOPPER_PROTOCOL_HPP
hpp
asio
data/projects/asio/example/cpp11/porthopper/client.cpp
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <algorithm> #include <cstdlib> #include <exception> #include <iostream> #include <memory> #include <string> #include <utility> #include "protocol.hpp" using boost::asio::ip::tcp; using boost::asio::ip::udp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: client <host> <port>\n"; return 1; } using namespace std; // For atoi. std::string host_name = argv[1]; std::string port = argv[2]; boost::asio::io_context io_context; // Determine the location of the server. tcp::resolver resolver(io_context); tcp::endpoint remote_endpoint = *resolver.resolve(host_name, port).begin(); // Establish the control connection to the server. tcp::socket control_socket(io_context); control_socket.connect(remote_endpoint); // Create a datagram socket to receive data from the server. udp::socket data_socket(io_context, udp::endpoint(udp::v4(), 0)); // Determine what port we will receive data on. udp::endpoint data_endpoint = data_socket.local_endpoint(); // Ask the server to start sending us data. control_request start = control_request::start(data_endpoint.port()); boost::asio::write(control_socket, start.to_buffers()); unsigned long last_frame_number = 0; for (;;) { // Receive 50 messages on the current data socket. for (int i = 0; i < 50; ++i) { // Receive a frame from the server. frame f; data_socket.receive(f.to_buffers(), 0); if (f.number() > last_frame_number) { last_frame_number = f.number(); std::cout << "\n" << f.payload(); } } // Time to switch to a new socket. To ensure seamless handover we will // continue to receive packets using the old socket until data arrives on // the new one. std::cout << " Starting renegotiation"; // Create the new data socket. udp::socket new_data_socket(io_context, udp::endpoint(udp::v4(), 0)); // Determine the new port we will use to receive data. udp::endpoint new_data_endpoint = new_data_socket.local_endpoint(); // Ask the server to switch over to the new port. control_request change = control_request::change( data_endpoint.port(), new_data_endpoint.port()); boost::system::error_code control_result; boost::asio::async_write(control_socket, change.to_buffers(), [&](boost::system::error_code ec, std::size_t /*length*/) { control_result = ec; }); // Try to receive a frame from the server on the new data socket. If we // successfully receive a frame on this new data socket we can consider // the renegotation complete. In that case we will close the old data // socket, which will cause any outstanding receive operation on it to be // cancelled. frame f1; boost::system::error_code new_data_socket_result; new_data_socket.async_receive(f1.to_buffers(), [&](boost::system::error_code ec, std::size_t /*length*/) { new_data_socket_result = ec; if (!ec) { // We have successfully received a frame on the new data socket, // so we can close the old data socket. This will cancel any // outstanding receive operation on the old data socket. data_socket.close(); } }); // This loop will continue until we have successfully completed the // renegotiation (i.e. received a frame on the new data socket), or some // unrecoverable error occurs. bool done = false; while (!done) { // Even though we're performing a renegotation, we want to continue // receiving data as smoothly as possible. Therefore we will continue to // try to receive a frame from the server on the old data socket. If we // receive a frame on this socket we will interrupt the io_context, // print the frame, and resume waiting for the other operations to // complete. frame f2; done = true; // Let's be optimistic. if (data_socket.is_open()) // May have been closed by receive handler. { data_socket.async_receive(f2.to_buffers(), 0, [&](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { // We have successfully received a frame on the old data // socket. Stop the io_context so that we can print it. io_context.stop(); done = false; } }); } // Run the operations in parallel. This will block until all operations // have finished, or until the io_context is interrupted. (No threads!) io_context.restart(); io_context.run(); // If the io_context.run() was interrupted then we have received a frame // on the old data socket. We need to keep waiting for the renegotation // operations to complete. if (!done) { if (f2.number() > last_frame_number) { last_frame_number = f2.number(); std::cout << "\n" << f2.payload(); } } } // Since the loop has finished, we have either successfully completed // the renegotation, or an error has occurred. First we'll check for // errors. if (control_result) throw boost::system::system_error(control_result); if (new_data_socket_result) throw boost::system::system_error(new_data_socket_result); // If we get here it means we have successfully started receiving data on // the new data socket. This new data socket will be used from now on // (until the next time we renegotiate). std::cout << " Renegotiation complete"; data_socket = std::move(new_data_socket); data_endpoint = new_data_endpoint; if (f1.number() > last_frame_number) { last_frame_number = f1.number(); std::cout << "\n" << f1.payload(); } } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/socks4/sync_client.cpp
// // sync_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <iostream> #include <iomanip> #include <ostream> #include <string> #include <boost/asio.hpp> #include "socks4.hpp" using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 4) { std::cout << "Usage: sync_client <socks4server> <socks4port> <user>\n"; std::cout << "Examples:\n"; std::cout << " sync_client 127.0.0.1 1080 chris\n"; std::cout << " sync_client localhost socks chris\n"; return 1; } boost::asio::io_context io_context; // Get a list of endpoints corresponding to the SOCKS 4 server name. tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); // Try each endpoint until we successfully establish a connection to the // SOCKS 4 server. tcp::socket socket(io_context); boost::asio::connect(socket, endpoints); // Get an endpoint for the Boost website. This will be passed to the SOCKS // 4 server. Explicitly specify IPv4 since SOCKS 4 does not support IPv6. auto http_endpoint = *resolver.resolve(tcp::v4(), "www.boost.org", "http").begin(); // Send the request to the SOCKS 4 server. socks4::request socks_request( socks4::request::connect, http_endpoint, argv[3]); boost::asio::write(socket, socks_request.buffers()); // Receive a response from the SOCKS 4 server. socks4::reply socks_reply; boost::asio::read(socket, socks_reply.buffers()); // Check whether we successfully negotiated with the SOCKS 4 server. if (!socks_reply.success()) { std::cout << "Connection failed.\n"; std::cout << "status = 0x" << std::hex << socks_reply.status(); return 1; } // Form the HTTP request. We specify the "Connection: close" header so that // the server will close the socket after transmitting the response. This // will allow us to treat all data up until the EOF as the response. std::string request = "GET / HTTP/1.0\r\n" "Host: www.boost.org\r\n" "Accept: */*\r\n" "Connection: close\r\n\r\n"; // Send the HTTP request. boost::asio::write(socket, boost::asio::buffer(request)); // Read until EOF, writing data to output as we go. std::array<char, 512> response; boost::system::error_code error; while (std::size_t s = socket.read_some( boost::asio::buffer(response), error)) std::cout.write(response.data(), s); if (error != boost::asio::error::eof) throw boost::system::system_error(error); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/socks4/socks4.hpp
// // socks4.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef SOCKS4_HPP #define SOCKS4_HPP #include <array> #include <string> #include <boost/asio/buffer.hpp> #include <boost/asio/ip/tcp.hpp> namespace socks4 { const unsigned char version = 0x04; class request { public: enum command_type { connect = 0x01, bind = 0x02 }; request(command_type cmd, const boost::asio::ip::tcp::endpoint& endpoint, const std::string& user_id) : version_(version), command_(cmd), user_id_(user_id), null_byte_(0) { // Only IPv4 is supported by the SOCKS 4 protocol. if (endpoint.protocol() != boost::asio::ip::tcp::v4()) { throw boost::system::system_error( boost::asio::error::address_family_not_supported); } // Convert port number to network byte order. unsigned short port = endpoint.port(); port_high_byte_ = (port >> 8) & 0xff; port_low_byte_ = port & 0xff; // Save IP address in network byte order. address_ = endpoint.address().to_v4().to_bytes(); } std::array<boost::asio::const_buffer, 7> buffers() const { return { { boost::asio::buffer(&version_, 1), boost::asio::buffer(&command_, 1), boost::asio::buffer(&port_high_byte_, 1), boost::asio::buffer(&port_low_byte_, 1), boost::asio::buffer(address_), boost::asio::buffer(user_id_), boost::asio::buffer(&null_byte_, 1) } }; } private: unsigned char version_; unsigned char command_; unsigned char port_high_byte_; unsigned char port_low_byte_; boost::asio::ip::address_v4::bytes_type address_; std::string user_id_; unsigned char null_byte_; }; class reply { public: enum status_type { request_granted = 0x5a, request_failed = 0x5b, request_failed_no_identd = 0x5c, request_failed_bad_user_id = 0x5d }; reply() : null_byte_(0), status_() { } std::array<boost::asio::mutable_buffer, 5> buffers() { return { { boost::asio::buffer(&null_byte_, 1), boost::asio::buffer(&status_, 1), boost::asio::buffer(&port_high_byte_, 1), boost::asio::buffer(&port_low_byte_, 1), boost::asio::buffer(address_) } }; } bool success() const { return null_byte_ == 0 && status_ == request_granted; } unsigned char status() const { return status_; } boost::asio::ip::tcp::endpoint endpoint() const { unsigned short port = port_high_byte_; port = (port << 8) & 0xff00; port = port | port_low_byte_; boost::asio::ip::address_v4 address(address_); return boost::asio::ip::tcp::endpoint(address, port); } private: unsigned char null_byte_; unsigned char status_; unsigned char port_high_byte_; unsigned char port_low_byte_; boost::asio::ip::address_v4::bytes_type address_; }; } // namespace socks4 #endif // SOCKS4_HPP
hpp
asio
data/projects/asio/example/cpp11/invocation/prioritised_handlers.cpp
// // prioritised_handlers.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> #include <memory> #include <queue> using boost::asio::ip::tcp; class handler_priority_queue : public boost::asio::execution_context { public: template <typename Function> void add(int priority, Function function) { std::unique_ptr<queued_handler_base> handler( new queued_handler<Function>( priority, std::move(function))); handlers_.push(std::move(handler)); } void execute_all() { while (!handlers_.empty()) { handlers_.top()->execute(); handlers_.pop(); } } class executor { public: executor(handler_priority_queue& q, int p) : context_(q), priority_(p) { } handler_priority_queue& context() const noexcept { return context_; } template <typename Function, typename Allocator> void dispatch(Function f, const Allocator&) const { context_.add(priority_, std::move(f)); } template <typename Function, typename Allocator> void post(Function f, const Allocator&) const { context_.add(priority_, std::move(f)); } template <typename Function, typename Allocator> void defer(Function f, const Allocator&) const { context_.add(priority_, std::move(f)); } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} bool operator==(const executor& other) const noexcept { return &context_ == &other.context_ && priority_ == other.priority_; } bool operator!=(const executor& other) const noexcept { return !operator==(other); } private: handler_priority_queue& context_; int priority_; }; template <typename Handler> boost::asio::executor_binder<Handler, executor> wrap(int priority, Handler handler) { return boost::asio::bind_executor( executor(*this, priority), std::move(handler)); } private: class queued_handler_base { public: queued_handler_base(int p) : priority_(p) { } virtual ~queued_handler_base() { } virtual void execute() = 0; friend bool operator<(const std::unique_ptr<queued_handler_base>& a, const std::unique_ptr<queued_handler_base>& b) noexcept { return a->priority_ < b->priority_; } private: int priority_; }; template <typename Function> class queued_handler : public queued_handler_base { public: queued_handler(int p, Function f) : queued_handler_base(p), function_(std::move(f)) { } void execute() override { function_(); } private: Function function_; }; std::priority_queue<std::unique_ptr<queued_handler_base>> handlers_; }; //---------------------------------------------------------------------- void high_priority_handler(const boost::system::error_code& /*ec*/, tcp::socket /*socket*/) { std::cout << "High priority handler\n"; } void middle_priority_handler(const boost::system::error_code& /*ec*/) { std::cout << "Middle priority handler\n"; } struct low_priority_handler { // Make the handler a move-only type. low_priority_handler() = default; low_priority_handler(const low_priority_handler&) = delete; low_priority_handler(low_priority_handler&&) = default; void operator()() { std::cout << "Low priority handler\n"; } }; int main() { boost::asio::io_context io_context; handler_priority_queue pri_queue; // Post a completion handler to be run immediately. boost::asio::post(io_context, pri_queue.wrap(0, low_priority_handler())); // Start an asynchronous accept that will complete immediately. tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 0); tcp::acceptor acceptor(io_context, endpoint); tcp::socket server_socket(io_context); acceptor.async_accept(pri_queue.wrap(100, high_priority_handler)); tcp::socket client_socket(io_context); client_socket.connect(acceptor.local_endpoint()); // Set a deadline timer to expire immediately. boost::asio::steady_timer timer(io_context); timer.expires_at(boost::asio::steady_timer::clock_type::time_point::min()); timer.async_wait(pri_queue.wrap(42, middle_priority_handler)); while (io_context.run_one()) { // The custom invocation hook adds the handlers to the priority queue // rather than executing them from within the poll_one() call. while (io_context.poll_one()) ; pri_queue.execute_all(); } return 0; }
cpp
asio
data/projects/asio/example/cpp11/deferred/deferred_2.cpp
// // deferred_2.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); auto deferred_op = timer.async_wait( deferred( [&](boost::system::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) ); std::move(deferred_op)( [](boost::system::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp11/deferred/deferred_1.cpp
// // deferred_1.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <iostream> using boost::asio::deferred; int main() { boost::asio::io_context ctx; boost::asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); auto deferred_op = timer.async_wait(deferred); std::move(deferred_op)( [](boost::system::error_code ec) { std::cout << "timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp11/windows/transmit_file.cpp
// // transmit_file.cpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <ctime> #include <functional> #include <iostream> #include <memory> #include <string> #include <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_WINDOWS_OVERLAPPED_PTR) using boost::asio::ip::tcp; using boost::asio::windows::overlapped_ptr; using boost::asio::windows::random_access_handle; typedef boost::asio::basic_stream_socket<tcp, boost::asio::io_context::executor_type> tcp_socket; typedef boost::asio::basic_socket_acceptor<tcp, boost::asio::io_context::executor_type> tcp_acceptor; // A wrapper for the TransmitFile overlapped I/O operation. template <typename Handler> void transmit_file(tcp_socket& socket, random_access_handle& file, Handler handler) { // Construct an OVERLAPPED-derived object to contain the handler. overlapped_ptr overlapped(socket.get_executor().context(), handler); // Initiate the TransmitFile operation. BOOL ok = ::TransmitFile(socket.native_handle(), file.native_handle(), 0, 0, overlapped.get(), 0, 0); DWORD last_error = ::GetLastError(); // Check if the operation completed immediately. if (!ok && last_error != ERROR_IO_PENDING) { // The operation completed immediately, so a completion notification needs // to be posted. When complete() is called, ownership of the OVERLAPPED- // derived object passes to the io_context. boost::system::error_code ec(last_error, boost::asio::error::get_system_category()); overlapped.complete(ec, 0); } else { // The operation was successfully initiated, so ownership of the // OVERLAPPED-derived object has passed to the io_context. overlapped.release(); } } class connection : public std::enable_shared_from_this<connection> { public: typedef std::shared_ptr<connection> pointer; static pointer create(boost::asio::io_context& io_context, const std::string& filename) { return pointer(new connection(io_context, filename)); } tcp_socket& socket() { return socket_; } void start() { boost::system::error_code ec; file_.assign(::CreateFile(filename_.c_str(), GENERIC_READ, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0), ec); if (file_.is_open()) { transmit_file(socket_, file_, std::bind(&connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } private: connection(boost::asio::io_context& io_context, const std::string& filename) : socket_(io_context), filename_(filename), file_(io_context) { } void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { boost::system::error_code ignored_ec; socket_.shutdown(tcp_socket::shutdown_both, ignored_ec); } tcp_socket socket_; std::string filename_; random_access_handle file_; }; class server { public: server(boost::asio::io_context& io_context, unsigned short port, const std::string& filename) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)), filename_(filename) { start_accept(); } private: void start_accept() { connection::pointer new_connection = connection::create(acceptor_.get_executor().context(), filename_); acceptor_.async_accept(new_connection->socket(), std::bind(&server::handle_accept, this, new_connection, boost::asio::placeholders::error)); } void handle_accept(connection::pointer new_connection, const boost::system::error_code& error) { if (!error) { new_connection->start(); } start_accept(); } tcp_acceptor acceptor_; std::string filename_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: transmit_file <port> <filename>\n"; return 1; } boost::asio::io_context io_context; using namespace std; // For atoi. server s(io_context, atoi(argv[1]), argv[2]); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } #else // defined(BOOST_ASIO_HAS_WINDOWS_OVERLAPPED_PTR) # error Overlapped I/O not available on this platform #endif // defined(BOOST_ASIO_HAS_WINDOWS_OVERLAPPED_PTR)
cpp
asio
data/projects/asio/example/cpp11/timers/time_t_timer.cpp
// // time_t_timer.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio.hpp> #include <ctime> #include <chrono> #include <iostream> // A custom implementation of the Clock concept from the standard C++ library. struct time_t_clock { // The duration type. typedef std::chrono::steady_clock::duration duration; // The duration's underlying arithmetic representation. typedef duration::rep rep; // The ratio representing the duration's tick period. typedef duration::period period; // An absolute time point represented using the clock. typedef std::chrono::time_point<time_t_clock> time_point; // The clock is not monotonically increasing. static constexpr bool is_steady = false; // Get the current time. static time_point now() noexcept { return time_point() + std::chrono::seconds(std::time(0)); } }; // The boost::asio::basic_waitable_timer template accepts an optional WaitTraits // template parameter. The underlying time_t clock has one-second granularity, // so these traits may be customised to reduce the latency between the clock // ticking over and a wait operation's completion. When the timeout is near // (less than one second away) we poll the clock more frequently to detect the // time change closer to when it occurs. The user can select the appropriate // trade off between accuracy and the increased CPU cost of polling. In extreme // cases, a zero duration may be returned to make the timers as accurate as // possible, albeit with 100% CPU usage. struct time_t_wait_traits { // Determine how long until the clock should be next polled to determine // whether the duration has elapsed. static time_t_clock::duration to_wait_duration( const time_t_clock::duration& d) { if (d > std::chrono::seconds(1)) return d - std::chrono::seconds(1); else if (d > std::chrono::seconds(0)) return std::chrono::milliseconds(10); else return std::chrono::seconds(0); } // Determine how long until the clock should be next polled to determine // whether the absoluate time has been reached. static time_t_clock::duration to_wait_duration( const time_t_clock::time_point& t) { return to_wait_duration(t - time_t_clock::now()); } }; typedef boost::asio::basic_waitable_timer< time_t_clock, time_t_wait_traits> time_t_timer; int main() { try { boost::asio::io_context io_context; time_t_timer timer(io_context); timer.expires_after(std::chrono::seconds(5)); std::cout << "Starting synchronous wait\n"; timer.wait(); std::cout << "Finished synchronous wait\n"; timer.expires_after(std::chrono::seconds(5)); std::cout << "Starting asynchronous wait\n"; timer.async_wait( [](const boost::system::error_code& /*error*/) { std::cout << "timeout\n"; }); io_context.run(); std::cout << "Finished asynchronous wait\n"; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime4/client.cpp
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::udp; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: client <host>" << std::endl; return 1; } boost::asio::io_context io_context; udp::resolver resolver(io_context); udp::endpoint receiver_endpoint = *resolver.resolve(udp::v4(), argv[1], "daytime").begin(); udp::socket socket(io_context); socket.open(udp::v4()); std::array<char, 1> send_buf = {{ 0 }}; socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint); std::array<char, 128> recv_buf; udp::endpoint sender_endpoint; size_t len = socket.receive_from( boost::asio::buffer(recv_buf), sender_endpoint); std::cout.write(recv_buf.data(), len); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/timer4/timer.cpp
// // timer.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <functional> #include <iostream> #include <boost/asio.hpp> class printer { public: printer(boost::asio::io_context& io) : timer_(io, boost::asio::chrono::seconds(1)), count_(0) { timer_.async_wait(std::bind(&printer::print, this)); } ~printer() { std::cout << "Final count is " << count_ << std::endl; } void print() { if (count_ < 5) { std::cout << count_ << std::endl; ++count_; timer_.expires_at(timer_.expiry() + boost::asio::chrono::seconds(1)); timer_.async_wait(std::bind(&printer::print, this)); } } private: boost::asio::steady_timer timer_; int count_; }; int main() { boost::asio::io_context io; printer p(io); io.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/timer5/timer.cpp
// // timer.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <functional> #include <iostream> #include <thread> #include <boost/asio.hpp> class printer { public: printer(boost::asio::io_context& io) : strand_(boost::asio::make_strand(io)), timer1_(io, boost::asio::chrono::seconds(1)), timer2_(io, boost::asio::chrono::seconds(1)), count_(0) { timer1_.async_wait(boost::asio::bind_executor(strand_, std::bind(&printer::print1, this))); timer2_.async_wait(boost::asio::bind_executor(strand_, std::bind(&printer::print2, this))); } ~printer() { std::cout << "Final count is " << count_ << std::endl; } void print1() { if (count_ < 10) { std::cout << "Timer 1: " << count_ << std::endl; ++count_; timer1_.expires_at(timer1_.expiry() + boost::asio::chrono::seconds(1)); timer1_.async_wait(boost::asio::bind_executor(strand_, std::bind(&printer::print1, this))); } } void print2() { if (count_ < 10) { std::cout << "Timer 2: " << count_ << std::endl; ++count_; timer2_.expires_at(timer2_.expiry() + boost::asio::chrono::seconds(1)); timer2_.async_wait(boost::asio::bind_executor(strand_, std::bind(&printer::print2, this))); } } private: boost::asio::strand<boost::asio::io_context::executor_type> strand_; boost::asio::steady_timer timer1_; boost::asio::steady_timer timer2_; int count_; }; int main() { boost::asio::io_context io; printer p(io); std::thread t([&]{ io.run(); }); io.run(); t.join(); return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime5/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::udp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_context io_context; udp::socket socket(io_context, udp::endpoint(udp::v4(), 13)); for (;;) { std::array<char, 1> recv_buf; udp::endpoint remote_endpoint; socket.receive_from(boost::asio::buffer(recv_buf), remote_endpoint); std::string message = make_daytime_string(); boost::system::error_code ignored_error; socket.send_to(boost::asio::buffer(message), remote_endpoint, 0, ignored_error); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/timer1/timer.cpp
// // timer.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <boost/asio.hpp> int main() { boost::asio::io_context io; boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5)); t.wait(); std::cout << "Hello, world!" << std::endl; return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/timer2/timer.cpp
// // timer.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <boost/asio.hpp> void print(const boost::system::error_code& /*e*/) { std::cout << "Hello, world!" << std::endl; } int main() { boost::asio::io_context io; boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5)); t.async_wait(&print); io.run(); return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime3/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <ctime> #include <functional> #include <iostream> #include <memory> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } class tcp_connection : public std::enable_shared_from_this<tcp_connection> { public: typedef std::shared_ptr<tcp_connection> pointer; static pointer create(boost::asio::io_context& io_context) { return pointer(new tcp_connection(io_context)); } tcp::socket& socket() { return socket_; } void start() { message_ = make_daytime_string(); boost::asio::async_write(socket_, boost::asio::buffer(message_), std::bind(&tcp_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: tcp_connection(boost::asio::io_context& io_context) : socket_(io_context) { } void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { } tcp::socket socket_; std::string message_; }; class tcp_server { public: tcp_server(boost::asio::io_context& io_context) : io_context_(io_context), acceptor_(io_context, tcp::endpoint(tcp::v4(), 13)) { start_accept(); } private: void start_accept() { tcp_connection::pointer new_connection = tcp_connection::create(io_context_); acceptor_.async_accept(new_connection->socket(), std::bind(&tcp_server::handle_accept, this, new_connection, boost::asio::placeholders::error)); } void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) { if (!error) { new_connection->start(); } start_accept(); } boost::asio::io_context& io_context_; tcp::acceptor acceptor_; }; int main() { try { boost::asio::io_context io_context; tcp_server server(io_context); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime7/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <ctime> #include <functional> #include <iostream> #include <memory> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using boost::asio::ip::udp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } class tcp_connection : public std::enable_shared_from_this<tcp_connection> { public: typedef std::shared_ptr<tcp_connection> pointer; static pointer create(boost::asio::io_context& io_context) { return pointer(new tcp_connection(io_context)); } tcp::socket& socket() { return socket_; } void start() { message_ = make_daytime_string(); boost::asio::async_write(socket_, boost::asio::buffer(message_), std::bind(&tcp_connection::handle_write, shared_from_this())); } private: tcp_connection(boost::asio::io_context& io_context) : socket_(io_context) { } void handle_write() { } tcp::socket socket_; std::string message_; }; class tcp_server { public: tcp_server(boost::asio::io_context& io_context) : io_context_(io_context), acceptor_(io_context, tcp::endpoint(tcp::v4(), 13)) { start_accept(); } private: void start_accept() { tcp_connection::pointer new_connection = tcp_connection::create(io_context_); acceptor_.async_accept(new_connection->socket(), std::bind(&tcp_server::handle_accept, this, new_connection, boost::asio::placeholders::error)); } void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) { if (!error) { new_connection->start(); } start_accept(); } boost::asio::io_context& io_context_; tcp::acceptor acceptor_; }; class udp_server { public: udp_server(boost::asio::io_context& io_context) : socket_(io_context, udp::endpoint(udp::v4(), 13)) { start_receive(); } private: void start_receive() { socket_.async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, std::bind(&udp_server::handle_receive, this, boost::asio::placeholders::error)); } void handle_receive(const boost::system::error_code& error) { if (!error) { std::shared_ptr<std::string> message( new std::string(make_daytime_string())); socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_, std::bind(&udp_server::handle_send, this, message)); start_receive(); } } void handle_send(std::shared_ptr<std::string> /*message*/) { } udp::socket socket_; udp::endpoint remote_endpoint_; std::array<char, 1> recv_buffer_; }; int main() { try { boost::asio::io_context io_context; tcp_server server1(io_context); udp_server server2(io_context); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime1/client.cpp
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <iostream> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: client <host>" << std::endl; return 1; } boost::asio::io_context io_context; tcp::resolver resolver(io_context); tcp::resolver::results_type endpoints = resolver.resolve(argv[1], "daytime"); tcp::socket socket(io_context); boost::asio::connect(socket, endpoints); for (;;) { std::array<char, 128> buf; boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf), error); if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw boost::system::system_error(error); // Some other error. std::cout.write(buf.data(), len); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime2/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 13)); for (;;) { tcp::socket socket(io_context); acceptor.accept(socket); std::string message = make_daytime_string(); boost::system::error_code ignored_error; boost::asio::write(socket, boost::asio::buffer(message), ignored_error); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/daytime6/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <ctime> #include <functional> #include <iostream> #include <memory> #include <string> #include <boost/asio.hpp> using boost::asio::ip::udp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } class udp_server { public: udp_server(boost::asio::io_context& io_context) : socket_(io_context, udp::endpoint(udp::v4(), 13)) { start_receive(); } private: void start_receive() { socket_.async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, std::bind(&udp_server::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_receive(const boost::system::error_code& error, std::size_t /*bytes_transferred*/) { if (!error) { std::shared_ptr<std::string> message( new std::string(make_daytime_string())); socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_, std::bind(&udp_server::handle_send, this, message, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); start_receive(); } } void handle_send(std::shared_ptr<std::string> /*message*/, const boost::system::error_code& /*error*/, std::size_t /*bytes_transferred*/) { } udp::socket socket_; udp::endpoint remote_endpoint_; std::array<char, 1> recv_buffer_; }; int main() { try { boost::asio::io_context io_context; udp_server server(io_context); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/tutorial/timer3/timer.cpp
// // timer.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <functional> #include <iostream> #include <boost/asio.hpp> void print(const boost::system::error_code& /*e*/, boost::asio::steady_timer* t, int* count) { if (*count < 5) { std::cout << *count << std::endl; ++(*count); t->expires_at(t->expiry() + boost::asio::chrono::seconds(1)); t->async_wait(std::bind(print, boost::asio::placeholders::error, t, count)); } } int main() { boost::asio::io_context io; int count = 0; boost::asio::steady_timer t(io, boost::asio::chrono::seconds(1)); t.async_wait(std::bind(print, boost::asio::placeholders::error, &t, &count)); io.run(); std::cout << "Final count is " << count << std::endl; return 0; }
cpp
asio
data/projects/asio/example/cpp11/spawn/parallel_grep.cpp
// // parallel_grep.cpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/detached.hpp> #include <boost/asio/dispatch.hpp> #include <boost/asio/post.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/thread_pool.hpp> #include <fstream> #include <iostream> #include <string> using boost::asio::detached; using boost::asio::dispatch; using boost::asio::spawn; using boost::asio::strand; using boost::asio::thread_pool; using boost::asio::yield_context; int main(int argc, char* argv[]) { try { if (argc < 2) { std::cerr << "Usage: parallel_grep <string> <files...>\n"; return 1; } // We use a fixed size pool of threads for reading the input files. The // number of threads is automatically determined based on the number of // CPUs available in the system. thread_pool pool; // To prevent the output from being garbled, we use a strand to synchronise // printing. strand<thread_pool::executor_type> output_strand(pool.get_executor()); // Spawn a new coroutine for each file specified on the command line. std::string search_string = argv[1]; for (int argn = 2; argn < argc; ++argn) { std::string input_file = argv[argn]; spawn(pool, [=](yield_context yield) { std::ifstream is(input_file.c_str()); std::string line; std::size_t line_num = 0; while (std::getline(is, line)) { // If we find a match, send a message to the output. if (line.find(search_string) != std::string::npos) { dispatch(output_strand, [=] { std::cout << input_file << ':' << line << std::endl; }); } // Every so often we yield control to another coroutine. if (++line_num % 10 == 0) post(yield); } }, detached); } // Join the thread pool to wait for all the spawned tasks to complete. pool.join(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/spawn/echo_server.cpp
// // echo_server.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/write.hpp> #include <iostream> #include <memory> using boost::asio::ip::tcp; class session : public std::enable_shared_from_this<session> { public: explicit session(boost::asio::io_context& io_context, tcp::socket socket) : socket_(std::move(socket)), timer_(io_context), strand_(io_context.get_executor()) { } void go() { auto self(shared_from_this()); boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield) { try { char data[128]; for (;;) { timer_.expires_after(std::chrono::seconds(10)); std::size_t n = socket_.async_read_some(boost::asio::buffer(data), yield); boost::asio::async_write(socket_, boost::asio::buffer(data, n), yield); } } catch (std::exception& e) { socket_.close(); timer_.cancel(); } }, boost::asio::detached); boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield) { while (socket_.is_open()) { boost::system::error_code ignored_ec; timer_.async_wait(yield[ignored_ec]); if (timer_.expiry() <= boost::asio::steady_timer::clock_type::now()) socket_.close(); } }, boost::asio::detached); } private: tcp::socket socket_; boost::asio::steady_timer timer_; boost::asio::strand<boost::asio::io_context::executor_type> strand_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: echo_server <port>\n"; return 1; } boost::asio::io_context io_context; boost::asio::spawn(io_context, [&](boost::asio::yield_context yield) { tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), std::atoi(argv[1]))); for (;;) { boost::system::error_code ec; tcp::socket socket(io_context); acceptor.async_accept(socket, yield[ec]); if (!ec) { std::make_shared<session>(io_context, std::move(socket))->go(); } } }, [](std::exception_ptr e) { if (e) std::rethrow_exception(e); }); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp