高性能服务器开发之boost.asio实现原理

本文其实并不长篇大论介绍boost.asio是怎样实现的,而只提供一个源代码。这个代码是笔者之前学习asio时写的demo版asio,从附带的例子看,代码和boost.asio有95%的相似度。不过demo只实现了windows iocp的部分,而且只有异步。代码很少,也就1000行吧,编译不依赖c11,但示例代码用到了c11的bind,boost.asio的初学者也许可以拿来参考,不具备项目使用价值。

myasio代码下载

以下是deadline_timer的示例,其它server、client等网络部分示例就不贴了

#include <iostream>
#include <functional>
#include <asio/io_service.h>
#include <asio/deadline_timer.h>

void handle_timer(int error)  
{  
    std::cout << "handle_timer: " << error << std::endl;
}  

void handle_wait(int error,  
                 asio::deadline_timer& t,   
                 int& count)  
{  
    if(!error)  
    {  
        std::cout << "handle_wait: " << count << std::endl;  

        t.async_wait(1000, std::bind(handle_wait,   
            std::placeholders::_1,  
            std::ref(t),  
            std::ref(count)));  
        if (count++ == 10)  
        {  
            t.cancel();  
        }  
    }
    else
    {
        std::cout << "timer canceled" << std::endl; 
    }
}  

int main()
{
    const int wait_millisec = 1000;
    asio::io_service io_service;
    asio::deadline_timer t1(io_service);

    int count = 0;
    t1.async_wait(wait_millisec, handle_timer);

    asio::deadline_timer t2(io_service);
    t2.async_wait(wait_millisec, std::bind(handle_wait,   
        std::placeholders::_1,  
        std::ref(t2),  
        std::ref(count)));

    io_service.run();

    std::cout << "end" << std::endl;
    std::cin.get();
    return 0;
}
原文地址:https://www.cnblogs.com/junye/p/6077806.html