writing to socket
This commit is contained in:
parent
cbbf4ab7e2
commit
9ec38272fa
|
@ -78,3 +78,8 @@ add_executable(writing_tcp_sync
|
|||
src/chapter02_io/writing_tcp_sync.cpp
|
||||
src/sdk.h)
|
||||
target_link_libraries(writing_tcp_sync PRIVATE Threads::Threads)
|
||||
|
||||
add_executable(reading_tcp_sync
|
||||
src/chapter02_io/reading_tcp_sync.cpp
|
||||
src/sdk.h)
|
||||
target_link_libraries(reading_tcp_sync PRIVATE Threads::Threads)
|
||||
|
|
|
@ -0,0 +1,47 @@
|
|||
#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;
|
||||
}
|
Loading…
Reference in New Issue