提到http server,一般用到的都是Apache和nginx這樣的成熟軟件,但是,有的情況下,我們也許也會用一些非常輕量級的http server。
http server的c++輕量級實現里,Mongoose和tinyhttpd這兩個比較有名,而且很有參考價值。
Mongoose只有一個.h一個.c,而且能夠很好的跨平台。在工作中,有過Mongoose運用在PC軟件和android app的實踐,效果也還可以。
cesanta/mongoose: Mongoose Embedded Web Server Library - Mongoose is more than an embedded webserver. It is a multi-protocol embedded networking library with functions including TCP, HTTP client and server, WebSocket client and server, MQTT client and broker and much more.
https://github.com/cesanta/mongoose
tinyhttpd則更加精簡,僅有一個.c,500行代碼。但是麻雀雖小五臟俱全,許多人推薦tinyhttpd給新手閱讀。
Tiny HTTPd download | SourceForge.net
https://sourceforge.net/projects/tinyhttpd/
【源碼剖析】tinyhttpd —— C 語言實現最簡單的 HTTP 服務器 - Just Coding! - 博客頻道 - CSDN.NET
http://blog.csdn.net/jcjc918/article/details/42129311
接下來,考慮使用面向對象的思想,用c++再自己實現個極簡的http server。
1、仍然是常規的http_request_t、http_response_t、http_handler_t
2、http_server_t在start時開一個線程,監聽端口
3、接到客戶端請求時按行recv,並解析uri和http包
3、分配到特定的http_handler_t處理完,把返回內容按http協議send給客戶端