libuv 是一個高效能事件驅動網路程式庫,是 Node.js 的底層實現。經過我(Liigo)在實際項目中的深度應用,發現 libuv 在代碼品質、運行效率、網路輸送量、穩定性、跨平台等多方面都相當優秀,是一款不可多得的開源產品,可以說從品質到名氣都不差。libuv
的缺點是易用性太差,文檔嚴重不足,入手門檻較高。在這些方面它跟陳碩的muduo 庫差距很大,muduo的易用性太棒了,還有一本作者的專註《Linux多線程服務端編程:使用muduo C++網路程式庫》品質很高。muduo的效能應該很好,可惜僅它支援Linux系統,跨平台特性為零,而且C++編譯出來的可執行檔尺寸較大,部署到嵌入式平台時有很大的局限性。關於libuv和muduo的選擇,我(Liigo)的觀點是:如果條件允許使用muduo,我建議您優先考慮muduo;否則,libuv也是很好的方案。
好了,言歸正傳。因為項目需要在軟體中內嵌一個極簡單的Web Server,於是我用libuv寫了這個tinyweb,以下是全部原始碼:
#include "tinyweb.h"#include <uv.h>#include <stdlib.h>#include <stdio.h>#include <assert.h>#include <string.h>#include <memory.h>uv_tcp_t _server;uv_tcp_t _client;uv_loop_t* _loop;static void tinyweb_on_connection(uv_stream_t* server, int status);void tinyweb_start(uv_loop_t* loop, const char* ip, int port) {_loop = loop;uv_tcp_init(_loop, &_server);uv_tcp_bind(&_server, uv_ip4_addr(ip&&ip[0]?ip:"0.0.0.0", port));uv_listen((uv_stream_t*)&_server, 8, tinyweb_on_connection);}static void after_uv_close(uv_handle_t* handle) {free(handle); //uv_tcp_t* client}static void after_uv_write(uv_write_t* w, int status) {if(w->data)free(w->data);uv_close((uv_handle_t*)w->handle, after_uv_close); //close clientfree(w);}static void write_uv_data(uv_stream_t* stream, const void* data, unsigned int len, int need_copy_data) {if(data == NULL || len == 0) return;if(len ==(unsigned int)-1)len = strlen(data);void* newdata = (void*)data;if(need_copy_data) {newdata = malloc(len);memcpy(newdata, data, len);}uv_buf_t buf = uv_buf_init(newdata, len);uv_write_t* w = (uv_write_t*)malloc(sizeof(uv_write_t));w->data = need_copy_data ? newdata : NULL;//free w and w->data in after_uv_write()uv_write(w, stream, &buf, 1, after_uv_write);}static const char* http_respone = "HTTP/1.1 200 OK\r\n""Content-Type:text/html;charset=utf-8\r\n""Content-Length:11\r\n""\r\n""Hello world";static void tinyweb_on_connection(uv_stream_t* server, int status) {assert(server == (uv_stream_t*)&_server);if(status == 0) {uv_tcp_t* client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));uv_tcp_init(_loop, client);uv_accept((uv_stream_t*)&_server, (uv_stream_t*)client);write_uv_data((uv_stream_t*)client, http_respone, -1, 0);//close client after uv_write, and free it in after_uv_close()}}
啟動代碼:
#include "tinyweb.h"int main() {tinyweb_start(uv_default_loop(), "127.0.0.1", 8080);uv_run(uv_default_loop(), UV_RUN_DEFAULT);}