Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1482311
  • 博文数量: 181
  • 博客积分: 3308
  • 博客等级: 中校
  • 技术积分: 2227
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-03 12:03
个人简介

我是zoro

文章分类

全部博文(181)

文章存档

2015年(1)

2013年(35)

2012年(39)

2011年(50)

2010年(56)

分类: LINUX

2012-11-30 12:14:46

转自:http://www.cnblogs.com/wangkangluo1/archive/2012/05/08/2489450.html

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

 

 

阅读(3335) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~