From 1808ceaaf564933e9a9cb719ad5e5eaa1f32784a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Mon, 8 Apr 2024 07:38:08 +0300 Subject: [PATCH] sync client --- boost_boilerplate/CMakeLists.txt | 5 ++ .../src/chapter03_client/tcp_client_sync.cpp | 87 +++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 boost_boilerplate/src/chapter03_client/tcp_client_sync.cpp diff --git a/boost_boilerplate/CMakeLists.txt b/boost_boilerplate/CMakeLists.txt index b5145dc..f357035 100644 --- a/boost_boilerplate/CMakeLists.txt +++ b/boost_boilerplate/CMakeLists.txt @@ -108,3 +108,8 @@ add_executable(shutdown_and_close_socket_server src/chapter02_io/shutdown_and_close_socket_server.cpp src/sdk.h) target_link_libraries(shutdown_and_close_socket_server PRIVATE Threads::Threads) + +add_executable(tcp_client_sync + src/chapter03_client/tcp_client_sync.cpp + src/sdk.h) +target_link_libraries(tcp_client_sync PRIVATE Threads::Threads) diff --git a/boost_boilerplate/src/chapter03_client/tcp_client_sync.cpp b/boost_boilerplate/src/chapter03_client/tcp_client_sync.cpp new file mode 100644 index 0000000..a0ae1b8 --- /dev/null +++ b/boost_boilerplate/src/chapter03_client/tcp_client_sync.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include + +using namespace boost; +namespace net = boost::asio; +namespace sys = boost::system; +using namespace std; + +class SyncTCPClient +{ + net::io_context ios_; + net::ip::tcp::endpoint ep_; + net::ip::tcp::socket sock_; + public: + SyncTCPClient(const string& raw_ip_address, uint16_t port_num): + ep_(net::ip::address::from_string(raw_ip_address), port_num), + sock_(ios_) + { + sock_.open(ep_.protocol()); + } + + void connect() + { + sock_.connect(ep_); + } + + void close() + { + sock_.shutdown(net::ip::tcp::socket::shutdown_both); + sock_.close(); + } + + string EmulateLongComputationOp(uint16_t duration_sec) + { + string request = "EMULATE_LONG_COMP_OP "s + to_string(duration_sec) + "\n"s; + + SendRequest(request); + + return ReceiveResponse(); + } + + private: + void SendRequest(const string& request) + { + net::write(sock_, net::buffer(request)); + } + + string ReceiveResponse() + { + net::streambuf buf; + net::read_until(sock_, buf, '\n'); + istream input(&buf); + + string response; + getline(input, response); + + return response; + } +}; + +int main() +{ + string raw_ip_address = "127.0.0.1"; + const uint16_t port_num = 3333; + + try + { + SyncTCPClient client(raw_ip_address, port_num); + + client.connect(); + + cout << "Sending request to the server..." << endl; + + string response = client.EmulateLongComputationOp(10); + + cout << "Response received: " << response << endl; + client.close(); + } + catch (sys::system_error& e) + { + cout << "Error! " << e.what() << endl; + } + + return EXIT_SUCCESS; +}