高性能服務器開發之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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM