libevent evhttp学习——http服务端
生活随笔
收集整理的這篇文章主要介紹了
libevent evhttp学习——http服务端
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http服務端相對客戶端要簡單很多,我們仍舊使用libevent-2.1.5版本,服務端接口和2.0版本沒有區別
基本流程
http服務端使用到的借口函數及流程如下
創建event_base和evhttp
struct event_base *event_base_new(void); struct evhttp *evhttp_new(struct event_base *base);- 1
- 2
綁定地址和端口
int evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port);- 1
設置處理函數
void evhttp_set_gencb(struct evhttp *http,void (*cb)(struct evhttp_request *, void *), void *arg);- 1
- 2
派發事件循環
int event_base_dispatch(struct event_base *);- 1
完整代碼
服務器接收到請求后打印URL,并返回一段文本信息
#include "event2/http.h" #include "event2/event.h" #include "event2/buffer.h"#include <stdlib.h> #include <stdio.h>void HttpGenericCallback(struct evhttp_request* request, void* arg) {const struct evhttp_uri* evhttp_uri = evhttp_request_get_evhttp_uri(request);char url[8192];evhttp_uri_join(const_cast<struct evhttp_uri*>(evhttp_uri), url, 8192);printf("accept request url:%s\n", url);struct evbuffer* evbuf = evbuffer_new();if (!evbuf){printf("create evbuffer failed!\n");return ;}evbuffer_add_printf(evbuf, "Server response. Your request url is %s", url);evhttp_send_reply(request, HTTP_OK, "OK", evbuf);evbuffer_free(evbuf); }int main(int argc, char** argv) {if (argc != 2){printf("usage:%s port\n", argv[0]);return 1;}int port = atoi(argv[1]);if (port == 0){printf("port error:%s\n", argv[1]);return 1;}struct event_base* base = event_base_new();if (!base){printf("create event_base failed!\n");return 1;}struct evhttp* http = evhttp_new(base);if (!http){printf("create evhttp failed!\n");return 1;}if (evhttp_bind_socket(http, "0.0.0.0", port) != 0){printf("bind socket failed! port:%d\n", port);return 1;}evhttp_set_gencb(http, HttpGenericCallback, NULL);event_base_dispatch(base);return 0; }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
編譯
g++ http-server.cpp -I/opt/third_party/libevent/include -L/opt/third_party/libevent/lib -levent -o http-server總結
以上是生活随笔為你收集整理的libevent evhttp学习——http服务端的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JFreeChart插件使用
- 下一篇: 推动Windows的限制:句柄