libevent 实现http server

参考链接

 1 #include <sys/types.h>
 2 #include <sys/time.h>
 3 #include <stdlib.h>
 4 #include <err.h>
 5 
 6 #include <event.h>
 7 #include <evhttp.h>
 8 
 9 void
10 root_handler(struct evhttp_request *req, void *arg)
11 {
12         struct evbuffer *buf;
13 
14         buf = evbuffer_new();
15         if (buf == NULL)
16                 err(1, "failed to create response buffer");
17         evbuffer_add_printf(buf, "Hello World!/n");
18         evhttp_send_reply(req, HTTP_OK, "OK", buf);
19 }
20 
21 void
22 generic_handler(struct evhttp_request *req, void *arg)
23 {
24         struct evbuffer *buf;
25 
26         buf = evbuffer_new();
27         if (buf == NULL)
28                 err(1, "failed to create response buffer");
29         evbuffer_add_printf(buf, "Requested: %s/n", evhttp_request_uri(req));
30         evhttp_send_reply(req, HTTP_OK, "OK", buf);
31 }
32 
33 int
34 main(int argc, char **argv)
35 {
36         struct evhttp *httpd;
37 
38         event_init();
39         httpd = evhttp_start("0.0.0.0", 8080);
40 
41         /* Set a callback for requests to "/". */
42         evhttp_set_cb(httpd, "/", root_handler, NULL);
43 
44         /* Set a callback for all other requests. */
45         evhttp_set_gencb(httpd, generic_handler, NULL);
46 
47         event_dispatch();
48 
49         /* Not reached in this code as it is now. */
50 
51         evhttp_free(httpd);
52 
53         return 0;
54 }

 

编译

gcc -g main.c -o main -levent

 

 

posted @ 2012-05-08 05:09  wangkangluo1  阅读(4650)  评论(1编辑  收藏  举报