From ff01b716711b97c2fcaa709ea97f7650f106aa10 Mon Sep 17 00:00:00 2001 From: Miodrag Milanovic Date: Fri, 7 Oct 2016 14:13:19 +0200 Subject: Added ASIO networking library (nw) --- .../src/examples/cpp11/futures/daytime_client.cpp | 94 ++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 3rdparty/asio/src/examples/cpp11/futures/daytime_client.cpp (limited to '3rdparty/asio/src/examples/cpp11/futures/daytime_client.cpp') diff --git a/3rdparty/asio/src/examples/cpp11/futures/daytime_client.cpp b/3rdparty/asio/src/examples/cpp11/futures/daytime_client.cpp new file mode 100644 index 00000000000..0004e124ff6 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp11/futures/daytime_client.cpp @@ -0,0 +1,94 @@ +// +// daytime_client.cpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2016 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 +#include +#include +#include +#include +#include +#include + +using asio::ip::udp; + +void get_daytime(asio::io_context& io_context, const char* hostname) +{ + try + { + udp::resolver resolver(io_context); + + std::future endpoints = + resolver.async_resolve( + udp::v4(), hostname, "daytime", + 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 send_buf = {{ 0 }}; + std::future send_length = + socket.async_send_to(asio::buffer(send_buf), + *endpoints.get().begin(), // ... until here. This call may block. + 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 recv_buf; + udp::endpoint sender_endpoint; + std::future recv_length = + socket.async_receive_from( + asio::buffer(recv_buf), + sender_endpoint, + 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 (std::system_error& e) + { + std::cerr << e.what() << std::endl; + } +} + +int main(int argc, char* argv[]) +{ + try + { + if (argc != 2) + { + std::cerr << "Usage: daytime_client " << 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. + asio::io_context io_context; + auto work = 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; +} -- cgit v1.2.3-70-g09d2