文档详情

基于Libevent的HTTP Server.doc

发布:2017-06-16约7.31千字共8页下载文档
文本预览下载声明
基于Libevent的HTTP Server简单的Http Server 使用Libevent内置的http相关接口,可以很容易的构建一个Http Server,一个简单的Http Server如下: #include event2/event.h #include event2/buffer.h #include event2/http.h #include Winsock2.h #include stdlib.h #include stdio.h int init_win_socket() { WSADATA wsaData; if(WSAStartup(MAKEWORD(2,2) , wsaData) != 0) { return -1; } return 0; } void generic_handler(struct evhttp_request *req, void *arg) { struct evbuffer *buf = evbuffer_new(); if(!buf) { puts(failed to create response buffer \n); return; } evbuffer_add_printf(buf, Server Responsed. Requested: %s\n, evhttp_request_get_uri(req)); evhttp_send_reply(req, HTTP_OK, OK, buf); evbuffer_free(buf); } int main(int argc, char* argv[]) { #ifdef WIN32 init_win_socket(); #endif short http_port = 8081; char *http_addr = ; struct event_base * base = event_base_new(); struct evhttp * http_server = evhttp_new(base); if(!http_server) { return -1; } int ret = evhttp_bind_socket(http_server,http_addr,http_port); if(ret!=0) { return -1; } evhttp_set_gencb(http_server, generic_handler, NULL); printf(http server start OK! \n); event_base_dispatch(base); evhttp_free(http_server); WSACleanup(); return 0; } 通过Libevent的接口构建一个Http Server的过程如下: (1)初始化:在event_base上新建一个evhttp,将这个evhttp绑定到监听的IP和端口号。 (2)设置Http回调函数:使用evhttp_set_gencb设置Http Server的处理请求的回调函数。 (3)启动Http Server:等待请求进入事件循环。 在Http Server中使用定时器提供更新服务 #include event2/event.h #include event2/buffer.h #include event2/http.h #include sys/stat.h #include Winsock2.h #include assert.h #include string.h #include stdlib.h #include stdio.h #define DEFAULT_FILE F:\\Libevent\\LibeventTest\\Debug\\sample.txt char *filedata; time_t lasttime = 0; char filename[80]; int counter = 0; struct event *loadfile_event; struct timeval tv; void read_file() { unsigned long size = 0; char *data; struct stat buf; if(
显示全部
相似文档