#include <iostream>
#include <memory>
#include <array>
#include <boost/asio.hpp>
using namespace std;
using namespace boost::asio;
const int MAX_MESS_SIZE = 4096;
class Session : public enable_shared_from_this < Session >
{
public:
Session(ip::tcp::socket &st) : m_socket(st), m_buff({})
{
}
void write_to_socket()
{
auto shared_self(shared_from_this());
async_write(m_socket, buffer(m_buff), [this, shared_self](const boost::system::error_code &err, size_t length)
{
if (!err)
{
read_from_socket();
}
});
}
void read_from_socket()
{
auto shared_self(shared_from_this());
m_socket.async_read_some(buffer(m_buff), [this, shared_self](const boost::system::error_code &err, size_t length)
{
if (!err)
{
write_to_socket();
}
});
}
private:
ip::tcp::socket &m_socket;
array<char, MAX_MESS_SIZE> m_buff;
};
class Client
{
public:
Client(io_service &ios) : m_ios(ios), m_sock(m_ios)
{
}
void start_connect()
{
cout << "start connect" << endl;
auto ptr = make_shared<Session>(m_sock);
m_sock.async_connect(ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 8001), [this, ptr](const boost::system::error_code &err)
{
if (!err)
{
ptr->write_to_socket();
}
});
}
private:
io_service &m_ios;
ip::tcp::socket m_sock;
};
int main()
{
io_service io;
Client cli(io);
cli.start_connect();
io.run();
return 0;
}
客户端运行后:
运行服务端再运行客户端后: