客户端代码:
//#define BOOST_ASIO_ENABLE_HANDLER_TRACKING
#include<iostream>
#include<boost/asio.hpp>
#include<boost/asio/ip/tcp.hpp>
#include<syncstream>
#include<chrono>
#include<string>
#include<iomanip>
using namespace std;
using namespace boost::asio;
using namespace std::chrono;
//if use g++ complie in windows,write like this:
//g++ -o server
网页链接 -IC:\boost_1_80_0 -LC:\boost_1_80_0\stage\lib -lws2_32 -lwsock32
class client
{
typedef client this_type;
typedef ip::tcp::endpoint endpoint_type;
typedef ip::address address_type;
typedef ip::tcp::socket socket_type;
typedef shared_ptr<socket_type> sock_ptr;
typedef vector<char> buffer_type;
static const size_t MAXSIZE = 5;
private:
io_service m_io;
buffer_type m_buf;
endpoint_type m_ep;
public:
client()
:m_buf(MAXSIZE, 0), m_ep(address_type::from_string("127.0.0.1"), 6688)
{
start();
}
void run()
{
m_io.run();
}
private:
void start()
{
sock_ptr sock(new socket_type(m_io));
boost::system::error_code ec;
sock->async_connect(m_ep,
[this, sock](const boost::system::error_code& ec)
{
if (ec)
return;
cout << "receive from " << sock->remote_endpoint().address() << ": ";
sock->async_read_some(buffer(m_buf),
[this, sock](const boost::system::error_code& ec, std::size_t)
{
read_handler(ec, sock);
});
});
}
void read_handler(const boost::system::error_code& ec, sock_ptr sock)
{
if (ec)
return;
for (auto data : m_buf)cout << data;
m_buf.resize(MAXSIZE, 0);
sock->async_read_some(buffer(m_buf),
[this, sock](const boost::system::error_code& ec, std::size_t)
{
read_handler(ec, sock);
});
}
};
int main()
{
try
{
cout << "client start." << endl;
client cl;
cl.run();
}
catch (exception& e)
{
cout << e.what() << endl;
}
}