boost asio 异步

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值