?????? libevent庫使得高并發(fā)響應(yīng)HTTP Server的編寫變得很容易。整個過程包括如下幾部:初始化,創(chuàng)建HTTP Server, 指定callback, 進(jìn)入事件循環(huán)。另外在回調(diào)函數(shù)中,可以獲取客戶端請求(request的HTTP Header和參數(shù)等),進(jìn)行響應(yīng)的處理,再將結(jié)果發(fā)送給客戶端(response的HTTP Header和內(nèi)容,如html代碼)。
libevent除了設(shè)置generic的callback,還可以對特定的請求路徑設(shè)置對應(yīng)的callback(回調(diào)/處理函數(shù))。
示例代碼(方便日后參考編寫需要的HTTP server)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //for getopt, fork
#include <string.h> //for strcat
//for struct evkeyvalq
#include <sys/queue.h>
#include <event.h>
//for http
#include <evhttp.h>
#include <signal.h>
#define MYHTTPD_SIGNATURE "myhttpd v 0.0.1"
//處理模塊
void httpd_handler(struct evhttp_request *req, void *arg) {
char output[2048] = "\0";
char tmp[1024];
//獲取客戶端請求的URI(使用evhttp_request_uri或直接req->uri)
const char *uri;
uri = evhttp_request_uri(req);
sprintf(tmp, "uri=%s\n", uri);
strcat(output, tmp);
sprintf(tmp, "uri=%s\n", req->uri);
strcat(output, tmp);
//decoded uri
char *decoded_uri;
decoded_uri = evhttp_decode_uri(uri);
sprintf(tmp, "decoded_uri=%s\n", decoded_uri);
strcat(output, tmp);
//解析URI的參數(shù)(即GET方法的參數(shù))
struct evkeyvalq params;
evhttp_parse_query(decoded_uri, ¶ms);
sprintf(tmp, "q=%s\n", evhttp_find_header(¶ms, "q"));
strcat(output, tmp);
sprintf(tmp, "s=%s\n", evhttp_find_header(¶ms, "s"));
strcat(output, tmp);
free(decoded_uri);
//獲取POST方法的數(shù)據(jù)
char *post_data = (char *) EVBUFFER_DATA(req->input_buffer);
sprintf(tmp, "post_data=%s\n", post_data);
strcat(output, tmp);
/*
具體的:可以根據(jù)GET/POST的參數(shù)執(zhí)行相應(yīng)操作,然后將結(jié)果輸出
...
*/
/* 輸出到客戶端 */
//HTTP header
evhttp_add_header(req->output_headers, "Server", MYHTTPD_SIGNATURE);
evhttp_add_header(req->output_headers, "Content-Type", "text/plain; charset=UTF-8");
evhttp_add_header(req->output_headers, "Connection", "close");
//輸出的內(nèi)容
struct evbuffer *buf;
buf = evbuffer_new();
evbuffer_add_printf(buf, "It works!\n%s\n", output);
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
void show_help() {
char *help = "written by Min (http://54min.com)\n\n"
"-l <ip_addr> interface to listen on, default is 0.0.0.0\n"
"-p <num> port number to listen on, default is 1984\n"
"-d run as a deamon\n"
"-t <second> timeout for a http request, default is 120 seconds\n"
"-h print this help and exit\n"
"\n";
fprintf(stderr, help);
}
//當(dāng)向進(jìn)程發(fā)出SIGTERM/SIGHUP/SIGINT/SIGQUIT的時候,終止event的事件偵聽循環(huán)
void signal_handler(int sig) {
switch (sig) {
case SIGTERM:
case SIGHUP:
case SIGQUIT:
case SIGINT:
event_loopbreak(); //終止偵聽event_dispatch()的事件偵聽循環(huán),執(zhí)行之后的代碼
break;
}
}
int main(int argc, char *argv[]) {
//自定義信號處理函數(shù)
signal(SIGHUP, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGQUIT, signal_handler);
//默認(rèn)參數(shù)
char *httpd_option_listen = "0.0.0.0";
int httpd_option_port = 8080;
int httpd_option_daemon = 0;
int httpd_option_timeout = 120; //in seconds
//獲取參數(shù)
int c;
while ((c = getopt(argc, argv, "l:p:dt:h")) != -1) {
switch (c) {
case 'l' :
httpd_option_listen = optarg;
break;
case 'p' :
httpd_option_port = atoi(optarg);
break;
case 'd' :
httpd_option_daemon = 1;
break;
case 't' :
httpd_option_timeout = atoi(optarg);
break;
case 'h' :
default :
show_help();
exit(EXIT_SUCCESS);
}
}
//判斷是否設(shè)置了-d,以daemon運(yùn)行
if (httpd_option_daemon) {
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid > 0) {
//生成子進(jìn)程成功,退出父進(jìn)程
exit(EXIT_SUCCESS);
}
}
/* 使用libevent創(chuàng)建HTTP Server */
//初始化event API
event_init();
//創(chuàng)建一個http server
struct evhttp *httpd;
httpd = evhttp_start(httpd_option_listen, httpd_option_port);
evhttp_set_timeout(httpd, httpd_option_timeout);
//指定generic callback
evhttp_set_gencb(httpd, httpd_handler, NULL);
//也可以為特定的URI指定callback
//evhttp_set_cb(httpd, "/", specific_handler, NULL);
//循環(huán)處理events
event_dispatch();
evhttp_free(httpd);
return 0;
}
-
編譯:
gcc -o myhttpd -Wall -levent myhttpd.c
-
運(yùn)行:
./test
- 測試:
在瀏覽器中輸入
http://54min.com:8080/index.php?q=test&s=some thing
,顯示內(nèi)容如下:
It works!
uri=/index.php?q=test&s=some%20thing
uri=/index.php?q=test&s=some%20thing
decoded_uri=/index.php?q=test&s=some thing
q=test
s=some thing
post_data=(null)
并使用Live Http Headers(Firefox addons)查看HTTP headers。
HTTP/1.1 200 OK
Server: myhttpd v 0.0.1
Content-Type: text/plain; charset=UTF-8
Connection: close
Date: Tue, 21 Jun 2011 06:30:30 GMT
Content-Length: 72
使用libevent庫進(jìn)行HTTP封裝方法的 應(yīng)用
libevent庫使得編寫高并發(fā)高性能的HTTP Server變得很簡單。因此實際中,使用libevent可以為任何應(yīng)用(如數(shù)據(jù)庫)提供一個HTTP based的網(wǎng)絡(luò)接口,方便多個clients采用任何支持HTTP protocol的語言與server進(jìn)行交互。例如:
對不支持HTTP協(xié)議的數(shù)據(jù)庫(RDBMS/NoSQL)封裝HTTP接口
- Memcached Server默認(rèn)支持的是Memcached Protocol,通過libmemcached庫和libevent庫,可以為Memcached Server封裝一個HTTP接口,從而client端可通過HTTP協(xié)議和Memcached Server進(jìn)行交互; 參考 。
- 可為Tokyo Cabinet/Tokyo Tyrant數(shù)據(jù)庫封裝HTTP接口,方便client端與其交互。 參考
- 相同的,也可為其他數(shù)據(jù)庫如MySQL, Redis, MongoDB等封裝HTTP接口;
更多的該種應(yīng)用可以參考: https://github.com/bitly/simplehttp 。
也可以為某些應(yīng)用封裝HTTP接口,從而實現(xiàn)以client/server方式使用該應(yīng)用
附:涉及的數(shù)據(jù)結(jié)構(gòu)和主要函數(shù)
數(shù)據(jù)結(jié)構(gòu)
- struct evhttp_request
表示客戶端請求,定義參看:http://monkey.org/~provos/libevent/doxygen-1.4.10/structevhttp__request.html,其中包含的主要域:
struct evkeyvalq *input_headers; //保存客戶端請求的HTTP headers(key-value pairs)
struct evkeyvalq *output_headers; //保存將要發(fā)送到客戶端的HTTP headers(key-value pairs)
//客戶端的ip和port
char *remote_host;
u_short remote_port;
enum evhttp_request_kind kind; //可以是EVHTTP_REQUEST或EVHTTP_RESPONSE
enum evhttp_cmd_type type; //可以是EVHTTP_REQ_GET, EVHTTP_REQ_POST或EVHTTP_REQ_HEAD
char *uri; //客戶端請求的uri
char major; //HTTP major number
char minor; //HTTP major number
int response_code; //HTTP response code
char *response_code_line; //readable response
struct evbuffer *input_buffer; //客戶端POST的數(shù)據(jù)
struct evbuffer *output_buffer; //輸出到客戶端的數(shù)據(jù)
- struct evkeyvalq
定義參看:http://monkey.org/~provos/libevent/doxygen-1.4.10/event_8h-source.html。
struct evkeyvalq
被定義為
TAILQ_HEAD (evkeyvalq, evkeyval);
,即
struct evkeyval
類型的tail queue。需要在代碼之前包含
#include <sys/queue.h>
#include <event.h>
struct evkeyval
為key-value queue(隊列結(jié)構(gòu)),主要用來保存HTTP headers,也可以被用來保存parse uri參數(shù)的結(jié)果。
/* Key-Value pairs. Can be used for HTTP headers but also for query argument parsing. */
struct evkeyval {
TAILQ_ENTRY(evkeyval) next; //隊列
char *key;
char *value;
};
宏
TAILQ_ENTRY(evkeyval)
被定義為:
#define TAILQ_ENTRY(type)
struct {
struct type *tqe_next; //next element
struct type **tqe_prev; //address of previous next element
}
- stuct evbuffer
定義參看:http://monkey.org/~provos/libevent/doxygen-1.4.10/event_8h-source.html。該結(jié)構(gòu)體用于input和output的buffer。
/* These functions deal with buffering input and output */
struct evbuffer {
u_char *buffer;
u_char *orig_buffer;
size_t misalign;
size_t totallen;
size_t off;
void (*cb)(struct evbuffer *, size_t, size_t, void *);
void *cbarg;
};
另外定義宏方便獲取evbuffer中保存的內(nèi)容和大小:
#define EVBUFFER_LENGTH(x) (x)->off
#define EVBUFFER_DATA(x) (x)->buffer
例如,獲取客戶端POST數(shù)據(jù)的內(nèi)容和大小:
EVBUFFER_DATA(res->input_buffer);
EVBUFFER_LENGTH(res->input_buffer);
另外
struct evbuffer
用如下函數(shù)創(chuàng)建添加和釋放:
struct evbuffer *buf;
buf = evbuffer_new();
//往buffer中添加內(nèi)容
evbuffer_add_printf(buf, "It works! you just requested: %s\n", req->uri); //Append a formatted string to the end of an evbuffer.
//將內(nèi)容輸出到客戶端
evhttp_send_reply(req, HTTP_OK, "OK", buf);
//釋放掉buf
evbuffer_free(buf);
關(guān)鍵函數(shù)
- 獲取客戶端請求的URI
使用
req->uri
或使用函數(shù)
const char *evhttp_request_uri(struct evhttp_request *req);
即(
evhttp_request_uri(req);
)。
- 對獲取的URI進(jìn)行解析和其他操作
使用函數(shù)
void evhttp_parse_query(const char *uri, struct evkeyvalq *args);
可對uri的參數(shù)進(jìn)行解析,結(jié)果保存在
struct evkeyvalq
的key-value pairs中,例如:
char *uri = "http://foo.com/?q=test&s=some+thing";
struct evkeyvalq args;
evhttp_parse_query(uri, &args);
//然后通過evhttp_find_header等函數(shù)獲取各個參數(shù)及對應(yīng)的值
evhttp_find_header(&args, "q"); //得到test
evhttp_find_header(&args, "s"); //得到some thing
如下兩個函數(shù)對URI進(jìn)行encode和decode:
char *evhttp_encode_uri(const char *uri);
char *evhttp_decode_uri(const char *uri);
URI encode的結(jié)果是所有非alphanumeric及
-_
的字符都被類似于
%
和一個2位16進(jìn)制字符替換(其中空格被
+
號替換)。如上兩個函數(shù)返回的字符串需要
free
掉。
- 處理HTTP headers相關(guān)的函數(shù)
HTTP headers保存在
struct evkeyvalq
的結(jié)構(gòu)體中(key-value pairs),使用如下函數(shù)可對其進(jìn)行修改:
const char *evhttp_find_header(const struct evkeyvalq *, const char *);
int evhttp_remove_header(struct evkeyvalq *, const char *);
int evhttp_add_header(struct evkeyvalq *, const char *, const char *);
void evhttp_clear_headers(struct evkeyvalq *);
-
Escape特殊的HTML字符
char *evhttp_htmlescape(const char *html);
特殊字符:
&
被替換為
&
;
"
被替換為
"
;
'
被替換為
'
;
<
被替換為
<
;
>
被替換為
>
。該函數(shù)返回的字符串需要
free
掉。
轉(zhuǎn)載自:http://note.sdo.com/u/1730579924/n/D9ETk~jLB38MLX0a8000TB
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
