Boost Asio总结(16)异步通信例子

Posted thefist11

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Boost Asio总结(16)异步通信例子相关的知识,希望对你有一定的参考价值。

1. client

async_TcpClient::async_TcpClient(const tcp::endpoint &point):
    io_service(),
    endpoint(point),
    socket(io_service),
    async_timer(io_service)

    connect();
    io_service.run();
    std::cout<<"io_service.run() is end!"<<std::endl;


void async_TcpClient::connect() 
    socket.async_connect(endpoint,[this](const boost::system::error_code &ec)
        connect_handler(ec);
    );
    std::cout<<"connect()"<<std::endl;


void async_TcpClient::connect_handler(const boost::system::error_code &ec) 
    std::cout<<"connected!"<<ec.message()<<std::endl;
    boost::asio::write(socket,boost::asio::buffer("hello world!",1024));
//    std::cout<<"start another accept()"<<std::endl;
//    connect(); 

2. server

ansyc_tcpServer::ansyc_tcpServer() :
    io_service(),endpoint(tcp::v4(),2001), acceptor(io_service,endpoint),sock(new tcp::socket(io_service))
    accept();
    io_service.run();
    std::cout<<"io_service.run() is end"<<std::endl;


ansyc_tcpServer::~ansyc_tcpServer() 



void ansyc_tcpServer::accept() 
    acceptor.async_accept(*sock,[this](const boost::system::error_code &ec)
        handle_accept(ec);
    );
    std::cout<<"accept()"<<std::endl;


void ansyc_tcpServer::handle_accept(const boost::system::error_code &ec) 
    if(ec)
        return;
    
    read();
    std::cout<<"start another accept()"<<std::endl;
    accept();


void ansyc_tcpServer::read() 
    boost::asio::async_read(*sock,boost::asio::buffer(str,1024),[this](boost::system::error_code ec, std::size_t)
        if(!ec)
            write();
            std::cout<<"server received: "<<str<<std::endl;  //输出接收到的字符串
        
        read();
    );


void ansyc_tcpServer::write() 
    boost::asio::async_write(*sock,boost::asio::buffer("ok",2),[this](boost::system::error_code ec, std::size_t)
        if(!ec)
            std::cout<<"server recalled: "<<str<<" ok"<<std::endl;  //输出接收到的字符串
        
    );


【引用】

[1] 代码asio/eg2/async

以上是关于Boost Asio总结(16)异步通信例子的主要内容,如果未能解决你的问题,请参考以下文章

Boost Asio总结异步通信

boost::asio::ip::tcp实现网络通信的小例子

Boost Asio总结(16)例子

Boost Asio总结(16)httpServer例子

Boost Asio总结同步通信

Boost Asio总结概述