sync client
This commit is contained in:
parent
08281c918d
commit
1808ceaaf5
|
@ -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)
|
||||
|
|
|
@ -0,0 +1,87 @@
|
|||
#include <boost/asio.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
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;
|
||||
}
|
Loading…
Reference in New Issue