78 lines
1.6 KiB
C++
78 lines
1.6 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;
|
|
string buf;
|
|
size_t total_bytes_read;
|
|
};
|
|
|
|
void callback(const sys::error_code& ec,
|
|
size_t bytes_transferred,
|
|
std::shared_ptr<session> s)
|
|
{
|
|
if (ec)
|
|
{
|
|
cout << "Error! "s << ec.what() << endl;
|
|
|
|
return;
|
|
}
|
|
|
|
s->total_bytes_read += bytes_transferred;
|
|
|
|
if (s->total_bytes_read == s->buf.length())
|
|
{
|
|
return;
|
|
}
|
|
|
|
s->sock->async_write_some(net::buffer(s->buf.c_str() + s->total_bytes_read,
|
|
s->buf.length() - s->total_bytes_read),
|
|
std::bind(callback, placeholders::_1, placeholders::_2, s));
|
|
}
|
|
|
|
void WriteToSocket(std::shared_ptr<net::ip::tcp::socket> sock)
|
|
{
|
|
auto s = make_shared<session>();
|
|
|
|
s->buf = string {"Hello"};
|
|
s->total_bytes_read = 0;
|
|
s->sock = sock;
|
|
|
|
s->sock->async_write_some(
|
|
net::buffer(s->buf),
|
|
bind(callback, placeholders::_1, placeholders::_2, s)
|
|
);
|
|
}
|
|
|
|
int main()
|
|
{
|
|
string raw_ip_address = "127.0.0.1"s;
|
|
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);
|
|
|
|
WriteToSocket(sock);
|
|
ios.run();
|
|
}
|
|
catch (sys::system_error& e)
|
|
{
|
|
cout << "Error! " << e.what() << endl;
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|