diff options
Diffstat (limited to '3rdparty/asio/src/examples/cpp11/serialization')
4 files changed, 481 insertions, 0 deletions
diff --git a/3rdparty/asio/src/examples/cpp11/serialization/client.cpp b/3rdparty/asio/src/examples/cpp11/serialization/client.cpp new file mode 100644 index 00000000000..10ec87f6da4 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp11/serialization/client.cpp @@ -0,0 +1,125 @@ +// +// 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 <asio.hpp> +#include <functional> +#include <iostream> +#include <vector> +#include "connection.hpp" // Must come before boost/serialization headers. +#include <boost/serialization/vector.hpp> +#include "stock.hpp" + +namespace s11n_example { + +/// Downloads stock quote information from a server. +class client +{ +public: + /// Constructor starts the asynchronous connect operation. + client(asio::io_context& io_context, + const std::string& host, const std::string& service) + : connection_(io_context.get_executor()) + { + // Resolve the host name into an IP address. + asio::ip::tcp::resolver resolver(io_context); + asio::ip::tcp::resolver::query query(host, service); + asio::ip::tcp::resolver::iterator endpoint_iterator = + resolver.resolve(query); + + // Start an asynchronous connect operation. + asio::async_connect(connection_.socket(), endpoint_iterator, + std::bind(&client::handle_connect, this, + asio::placeholders::error)); + } + + /// Handle completion of a connect operation. + void handle_connect(const asio::error_code& e) + { + if (!e) + { + // Successfully established connection. Start operation to read the list + // of stocks. The connection::async_read() function will automatically + // decode the data that is read from the underlying socket. + connection_.async_read(stocks_, + std::bind(&client::handle_read, this, + asio::placeholders::error)); + } + else + { + // An error occurred. Log it and return. Since we are not starting a new + // operation the io_context will run out of work to do and the client will + // exit. + std::cerr << e.message() << std::endl; + } + } + + /// Handle completion of a read operation. + void handle_read(const asio::error_code& e) + { + if (!e) + { + // Print out the data that was received. + for (std::size_t i = 0; i < stocks_.size(); ++i) + { + std::cout << "Stock number " << i << "\n"; + std::cout << " code: " << stocks_[i].code << "\n"; + std::cout << " name: " << stocks_[i].name << "\n"; + std::cout << " open_price: " << stocks_[i].open_price << "\n"; + std::cout << " high_price: " << stocks_[i].high_price << "\n"; + std::cout << " low_price: " << stocks_[i].low_price << "\n"; + std::cout << " last_price: " << stocks_[i].last_price << "\n"; + std::cout << " buy_price: " << stocks_[i].buy_price << "\n"; + std::cout << " buy_quantity: " << stocks_[i].buy_quantity << "\n"; + std::cout << " sell_price: " << stocks_[i].sell_price << "\n"; + std::cout << " sell_quantity: " << stocks_[i].sell_quantity << "\n"; + } + } + else + { + // An error occurred. + std::cerr << e.message() << std::endl; + } + + // Since we are not starting a new operation the io_context will run out of + // work to do and the client will exit. + } + +private: + /// The connection to the server. + connection connection_; + + /// The data received from the server. + std::vector<stock> stocks_; +}; + +} // namespace s11n_example + +int main(int argc, char* argv[]) +{ + try + { + // Check command line arguments. + if (argc != 3) + { + std::cerr << "Usage: client <host> <port>" << std::endl; + return 1; + } + + asio::io_context io_context; + s11n_example::client client(io_context, argv[1], argv[2]); + io_context.run(); + } + catch (std::exception& e) + { + std::cerr << e.what() << std::endl; + } + + return 0; +} diff --git a/3rdparty/asio/src/examples/cpp11/serialization/connection.hpp b/3rdparty/asio/src/examples/cpp11/serialization/connection.hpp new file mode 100644 index 00000000000..14d96f7597b --- /dev/null +++ b/3rdparty/asio/src/examples/cpp11/serialization/connection.hpp @@ -0,0 +1,184 @@ +// +// connection.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 SERIALIZATION_CONNECTION_HPP +#define SERIALIZATION_CONNECTION_HPP + +#include <asio.hpp> +#include <boost/archive/text_iarchive.hpp> +#include <boost/archive/text_oarchive.hpp> +#include <functional> +#include <iomanip> +#include <memory> +#include <string> +#include <sstream> +#include <tuple> +#include <vector> + +namespace s11n_example { + +/// The connection class provides serialization primitives on top of a socket. +/** + * Each message sent using this class consists of: + * @li An 8-byte header containing the length of the serialized data in + * hexadecimal. + * @li The serialized data. + */ +class connection +{ +public: + /// Constructor. + connection(const asio::any_io_executor& ex) + : socket_(ex) + { + } + + /// Get the underlying socket. Used for making a connection or for accepting + /// an incoming connection. + asio::ip::tcp::socket& socket() + { + return socket_; + } + + /// Asynchronously write a data structure to the socket. + template <typename T, typename Handler> + void async_write(const T& t, Handler handler) + { + // Serialize the data first so we know how large it is. + std::ostringstream archive_stream; + boost::archive::text_oarchive archive(archive_stream); + archive << t; + outbound_data_ = archive_stream.str(); + + // Format the header. + std::ostringstream header_stream; + header_stream << std::setw(header_length) + << std::hex << outbound_data_.size(); + if (!header_stream || header_stream.str().size() != header_length) + { + // Something went wrong, inform the caller. + std::error_code error(asio::error::invalid_argument); + asio::post(socket_.get_executor(), std::bind(handler, error)); + return; + } + outbound_header_ = header_stream.str(); + + // Write the serialized data to the socket. We use "gather-write" to send + // both the header and the data in a single write operation. + std::vector<asio::const_buffer> buffers; + buffers.push_back(asio::buffer(outbound_header_)); + buffers.push_back(asio::buffer(outbound_data_)); + asio::async_write(socket_, buffers, handler); + } + + /// Asynchronously read a data structure from the socket. + template <typename T, typename Handler> + void async_read(T& t, Handler handler) + { + // Issue a read operation to read exactly the number of bytes in a header. + void (connection::*f)(const std::error_code&, T&, std::tuple<Handler>) + = &connection::handle_read_header<T, Handler>; + asio::async_read(socket_, asio::buffer(inbound_header_), + std::bind(f, + this, asio::placeholders::error, std::ref(t), + std::make_tuple(handler))); + } + + /// Handle a completed read of a message header. + template <typename T, typename Handler> + void handle_read_header(const std::error_code& e, + T& t, std::tuple<Handler> handler) + { + if (e) + { + std::get<0>(handler)(e); + } + else + { + // Determine the length of the serialized data. + std::istringstream is(std::string(inbound_header_, header_length)); + std::size_t inbound_data_size = 0; + if (!(is >> std::hex >> inbound_data_size)) + { + // Header doesn't seem to be valid. Inform the caller. + std::error_code error(asio::error::invalid_argument); + std::get<0>(handler)(error); + return; + } + + // Start an asynchronous call to receive the data. + inbound_data_.resize(inbound_data_size); + void (connection::*f)( + const std::error_code&, + T&, std::tuple<Handler>) + = &connection::handle_read_data<T, Handler>; + asio::async_read(socket_, asio::buffer(inbound_data_), + std::bind(f, this, + asio::placeholders::error, std::ref(t), handler)); + } + } + + /// Handle a completed read of message data. + template <typename T, typename Handler> + void handle_read_data(const std::error_code& e, + T& t, std::tuple<Handler> handler) + { + if (e) + { + std::get<0>(handler)(e); + } + else + { + // Extract the data structure from the data just received. + try + { + std::string archive_data(&inbound_data_[0], inbound_data_.size()); + std::istringstream archive_stream(archive_data); + boost::archive::text_iarchive archive(archive_stream); + archive >> t; + } + catch (std::exception& e) + { + // Unable to decode data. + std::error_code error(asio::error::invalid_argument); + std::get<0>(handler)(error); + return; + } + + // Inform caller that data has been received ok. + std::get<0>(handler)(e); + } + } + +private: + /// The underlying socket. + asio::ip::tcp::socket socket_; + + /// The size of a fixed length header. + enum { header_length = 8 }; + + /// Holds an outbound header. + std::string outbound_header_; + + /// Holds the outbound data. + std::string outbound_data_; + + /// Holds an inbound header. + char inbound_header_[header_length]; + + /// Holds the inbound data. + std::vector<char> inbound_data_; +}; + +typedef std::shared_ptr<connection> connection_ptr; + +} // namespace s11n_example + +#endif // SERIALIZATION_CONNECTION_HPP diff --git a/3rdparty/asio/src/examples/cpp11/serialization/server.cpp b/3rdparty/asio/src/examples/cpp11/serialization/server.cpp new file mode 100644 index 00000000000..a032e86dc78 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp11/serialization/server.cpp @@ -0,0 +1,122 @@ +// +// 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 <asio.hpp> +#include <functional> +#include <iostream> +#include <vector> +#include "connection.hpp" // Must come before boost/serialization headers. +#include <boost/serialization/vector.hpp> +#include "stock.hpp" + +namespace s11n_example { + +/// Serves stock quote information to any client that connects to it. +class server +{ +public: + /// Constructor opens the acceptor and starts waiting for the first incoming + /// connection. + server(asio::io_context& io_context, unsigned short port) + : acceptor_(io_context, + asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port)) + { + // Create the data to be sent to each client. + stock s; + s.code = "ABC"; + s.name = "A Big Company"; + s.open_price = 4.56; + s.high_price = 5.12; + s.low_price = 4.33; + s.last_price = 4.98; + s.buy_price = 4.96; + s.buy_quantity = 1000; + s.sell_price = 4.99; + s.sell_quantity = 2000; + stocks_.push_back(s); + s.code = "DEF"; + s.name = "Developer Entertainment Firm"; + s.open_price = 20.24; + s.high_price = 22.88; + s.low_price = 19.50; + s.last_price = 19.76; + s.buy_price = 19.72; + s.buy_quantity = 34000; + s.sell_price = 19.85; + s.sell_quantity = 45000; + stocks_.push_back(s); + + // Start an accept operation for a new connection. + connection_ptr new_conn(new connection(acceptor_.get_executor())); + acceptor_.async_accept(new_conn->socket(), + std::bind(&server::handle_accept, this, + asio::placeholders::error, new_conn)); + } + + /// Handle completion of a accept operation. + void handle_accept(const std::error_code& e, connection_ptr conn) + { + if (!e) + { + // Successfully accepted a new connection. Send the list of stocks to the + // client. The connection::async_write() function will automatically + // serialize the data structure for us. + conn->async_write(stocks_, + std::bind(&server::handle_write, this, + asio::placeholders::error, conn)); + } + + // Start an accept operation for a new connection. + connection_ptr new_conn(new connection(acceptor_.get_executor())); + acceptor_.async_accept(new_conn->socket(), + std::bind(&server::handle_accept, this, + asio::placeholders::error, new_conn)); + } + + /// Handle completion of a write operation. + void handle_write(const std::error_code& e, connection_ptr conn) + { + // Nothing to do. The socket will be closed automatically when the last + // reference to the connection object goes away. + } + +private: + /// The acceptor object used to accept incoming socket connections. + asio::ip::tcp::acceptor acceptor_; + + /// The data to be sent to each client. + std::vector<stock> stocks_; +}; + +} // namespace s11n_example + +int main(int argc, char* argv[]) +{ + try + { + // Check command line arguments. + if (argc != 2) + { + std::cerr << "Usage: server <port>" << std::endl; + return 1; + } + unsigned short port = std::stoi(argv[1]); + + asio::io_context io_context; + s11n_example::server server(io_context, port); + io_context.run(); + } + catch (std::exception& e) + { + std::cerr << e.what() << std::endl; + } + + return 0; +} diff --git a/3rdparty/asio/src/examples/cpp11/serialization/stock.hpp b/3rdparty/asio/src/examples/cpp11/serialization/stock.hpp new file mode 100644 index 00000000000..bb305518cae --- /dev/null +++ b/3rdparty/asio/src/examples/cpp11/serialization/stock.hpp @@ -0,0 +1,50 @@ +// +// stock.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 SERIALIZATION_STOCK_HPP +#define SERIALIZATION_STOCK_HPP + +#include <string> + +namespace s11n_example { + +/// Structure to hold information about a single stock. +struct stock +{ + std::string code; + std::string name; + double open_price; + double high_price; + double low_price; + double last_price; + double buy_price; + int buy_quantity; + double sell_price; + int sell_quantity; + + template <typename Archive> + void serialize(Archive& ar, const unsigned int version) + { + ar & code; + ar & name; + ar & open_price; + ar & high_price; + ar & low_price; + ar & last_price; + ar & buy_price; + ar & buy_quantity; + ar & sell_price; + ar & sell_quantity; + } +}; + +} // namespace s11n_example + +#endif // SERIALIZATION_STOCK_HPP |