writing to socket asymc
This commit is contained in:
parent
9ec38272fa
commit
acdc883626
|
@ -83,3 +83,8 @@ add_executable(reading_tcp_sync
|
||||||
src/chapter02_io/reading_tcp_sync.cpp
|
src/chapter02_io/reading_tcp_sync.cpp
|
||||||
src/sdk.h)
|
src/sdk.h)
|
||||||
target_link_libraries(reading_tcp_sync PRIVATE Threads::Threads)
|
target_link_libraries(reading_tcp_sync PRIVATE Threads::Threads)
|
||||||
|
|
||||||
|
add_executable(writing_tcp_async
|
||||||
|
src/chapter02_io/writing_tcp_async.cpp
|
||||||
|
src/sdk.h)
|
||||||
|
target_link_libraries(writing_tcp_async PRIVATE Threads::Threads)
|
||||||
|
|
|
@ -0,0 +1,77 @@
|
||||||
|
#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_written;
|
||||||
|
};
|
||||||
|
|
||||||
|
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_written += bytes_transferred;
|
||||||
|
|
||||||
|
if (s->total_bytes_written == s->buf.length())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
s->sock->async_write_some(net::buffer(s->buf.c_str() + s->total_bytes_written,
|
||||||
|
s->buf.length() - s->total_bytes_written),
|
||||||
|
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_written = 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;
|
||||||
|
}
|
Loading…
Reference in New Issue