#include <iostream>
#include <memory>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/system/system_error.hpp>
using namespace boost::asio::ip;
class Session : public std::enable_shared_from_this<Session>
{
public:
Session(boost::asio::io_service &ios) : m_socket(ios)
{
}
tcp::socket &get_socket()
{
return this->m_socket;
}
void start_read()
{
m_socket.async_read_some(boost::asio::buffer(buffer, max_length),
boost::bind(&Session::read_handle,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
void read_handle(const boost::system::error_code &error, size_t bytes_transferred)
{
if (!error)
{
/*m_socket.async_write_some(boost::asio::buffer(buffer, max_length),
boost::bind(&Session::write_handle,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));*/
boost::asio::async_write(m_socket, boost::asio::buffer(buffer, bytes_transferred),
boost::bind(&Session::write_handle,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
}
void write_handle(const boost::system::error_code &error, size_t bytes_transferred)
{
if (!error)
{
start_read();
}
}
private:
tcp::socket m_socket;
enum { max_length = 4096 };
char buffer[max_length]{};
};
class Server
{
public:
Server(boost::asio::io_service &ios, unsigned short port) : m_io_service(ios),
m_acceptor(m_io_service, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
void start_accept()
{
std::shared_ptr<Session> new_session(new Session(m_io_service));
m_acceptor.async_accept(new_session->get_socket(),
boost::bind(&Server::accept_handle, this, new_session, boost::asio::placeholders::error));
}
void accept_handle(std::shared_ptr<Session> sock, const boost::system::error_code &error)
{
if (!error)
{
sock->start_read();
}
start_accept();
}
private:
boost::asio::io_service &m_io_service;
tcp::acceptor m_acceptor;
};
int main()
{
try
{
boost::asio::io_service ios;
Server server(ios, 8888);
ios.run();
}
catch (const std::exception &e)
{
std::cerr << "Exception" << e.what() << std::endl;
}
return 0;
}
boost asio 异步
最新推荐文章于 2021-01-17 15:47:11 发布