78 lines
1.7 KiB
C++
78 lines
1.7 KiB
C++
#include <boost/asio.hpp>
|
|
#include <iostream>
|
|
#include <memory>
|
|
|
|
using namespace boost;
|
|
using namespace std;
|
|
namespace sys = boost::system;
|
|
namespace net = boost::asio;
|
|
|
|
struct session
|
|
{
|
|
std::shared_ptr<net::ip::tcp::socket> sock;
|
|
unique_ptr<char[]> buf;
|
|
size_t total_bytes_read;
|
|
uint32_t buf_size;
|
|
};
|
|
|
|
void Callback(const boost::system::error_code& ec,
|
|
size_t bytes_transferred,
|
|
std::shared_ptr<session> s)
|
|
{
|
|
if (ec)
|
|
{
|
|
cout << "Error!"s << ec.value() << " "s << ec.what() << endl;
|
|
|
|
return;
|
|
}
|
|
|
|
s->total_bytes_read += bytes_transferred;
|
|
|
|
if (s->total_bytes_read == s->buf_size) return;
|
|
|
|
s->sock->async_read_some(asio::buffer(s->buf.get() + s->total_bytes_read,
|
|
s->buf_size - s->total_bytes_read),
|
|
std::bind(Callback, placeholders::_1, placeholders::_2, s));
|
|
}
|
|
|
|
void ReadFromSocket(std::shared_ptr<net::ip::tcp::socket> sock)
|
|
{
|
|
auto s = make_unique<session>();
|
|
|
|
const uint32_t message_size = 7;
|
|
|
|
s->buf.reset(new char [message_size]);
|
|
s->total_bytes_read = 0;
|
|
s->sock = sock;
|
|
s->buf_size = message_size;
|
|
|
|
s->sock->async_read_some(asio::buffer(s->buf.get(), s->buf_size),
|
|
std::bind(Callback, placeholders::_1, placeholders::_2, s));
|
|
}
|
|
|
|
int main()
|
|
{
|
|
string raw_ip_address = "127.0.0.1"s;
|
|
unsigned short 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);
|
|
|
|
ReadFromSocket(sock);
|
|
|
|
ios.run();
|
|
}
|
|
catch (const sys::system_error& e)
|
|
{
|
|
cout << "Error!" << e.what() << endl;
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|