boost_asio/boost_boilerplate/src/chapter02_io/shutdown_and_close_socket.cpp

54 lines
1.0 KiB
C++

#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <thread>
using namespace boost;
namespace net = boost::asio;
namespace sys = boost::system;
using namespace std;
void Communicate(net::ip::tcp::socket& sock)
{
const char request_buf[] {0x48, 0x65, 0x6c, 0x6c, 0x6f};
net::write(sock, net::buffer(request_buf));
sock.shutdown(net::socket_base::shutdown_send);
net::streambuf response_buf;
sys::error_code ec;
net::read(sock, response_buf, ec);
if (ec == net::error::eof)
{
cout << "OK! End of file!"s << endl;
}
else
{
throw sys::system_error(ec);
}
}
int main()
{
string raw_ip_address = "127.0.0.1";
const uint16_t port_num = 3333;
try
{
net::ip::tcp::endpoint ep(net::ip::address::from_string(raw_ip_address), port_num);
net::io_context ios;
auto sock = make_shared<net::ip::tcp::socket>(ios, ep.protocol());
sock->connect(ep);
Communicate(*sock);
}
catch (const sys::system_error& err)
{
cout << "Error!" << err.what() << endl;
}
return EXIT_SUCCESS;
}