boost_asio/boost_boilerplate/src/chapter02_io/reading_tcp_sync.cpp

48 lines
1004 B
C++

#include <boost/asio.hpp>
#include <iostream>
#include <memory>
using namespace boost;
using namespace std;
namespace net = boost::asio;
string ReadFromSocket(net::ip::tcp::socket& sock)
{
constexpr unsigned char k_MessageSize = 6;
char buf[k_MessageSize];
size_t total_bytes_read = 0;
while (total_bytes_read != k_MessageSize)
{
total_bytes_read += sock.read_some(net::buffer(buf + total_bytes_read,
k_MessageSize - total_bytes_read));
}
return string {buf, total_bytes_read};
}
int main()
{
string raw_ip_address = "127.0.0.1";
size_t port_num = 3333;
try
{
net::ip::tcp::endpoint ep(net::ip::address::from_string(raw_ip_address),
port_num);
net::io_service ios;
net::ip::tcp::socket sock(ios, ep.protocol());
sock.connect(ep);
cout << ReadFromSocket(sock);
}
catch (const system::system_error& e)
{
cout << "Error!" << e.what() << endl;
}
return EXIT_SUCCESS;
}