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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值