基于libevent实现HttpServer

Http可以说是我们日常生活中最常用的一种请求-响应通信协议,基于TCP,最新版本为2.0。

典型的HTTP事务处理过程如下:

(1)客户与服务器建立连接;
(2)客户向服务器提出请求;
(3)服务器接受请求,并根据请求返回相应的文件作为应答;
(4)客户与服务器关闭连接。

实际C++项目中有遇到在业务代码中集成一个简单httpserver的需求,能够接受Get请求和Post请求,可以使用TCP封装Http协议报文的形式来实现,也可以使用现有的框架,本示例是基于开源框架libevent实现一个HttpServer。

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/********************************************************
Copyright (C), 2016-2018,
FileName: main
Author: 红烧肉
Email: CoderRoad666@163.com
Created: 2019/11/26
Description: 使用libevent实现http server功能
********************************************************/
#include <iostream>
#include <string.h>
#include <evhttp.h>
#include <event.h>
#include <string.h>

#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <event2/http.h>
#include <event2/bufferevent_compat.h>
#include <event2/http_struct.h>
#include <event2/http_compat.h>
#include <event2/util.h>
#include <event2/buffer.h>

#ifdef _WIN32
#include <windows.h>
#include <time.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#endif

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "wsock32.lib")
#pragma comment(lib, "libevent.lib")
#pragma comment(lib, "libevent_core.lib")
#pragma comment(lib, "libevent_extras.lib")

using namespace std;

#define BUF_MAX 1024*16

/************************************
@ Brief: 解析Post请求的数据
@ Author: woniu201
@ Created: 2019/11/26
@ Return:
************************************/
void get_post_message(char *buf, struct evhttp_request *req)
{
size_t post_size = 0;

post_size = evbuffer_get_length(req->input_buffer);//获取数据长度
printf("====line:%d,post len:%d\n",__LINE__,post_size);
if (post_size <= 0)
{
printf("====line:%d,post msg is empty!\n",__LINE__);
return;
}
else
{
size_t copy_len = post_size > BUF_MAX ? BUF_MAX : post_size;
printf("====line:%d,post len:%d, copy_len:%d\n",__LINE__,post_size,copy_len);
memcpy(buf, evbuffer_pullup(req->input_buffer,-1), copy_len);

buf[post_size] = '\0';
printf("====line:%d,post msg:%s\n",__LINE__,buf);
}
}

/************************************
@ Brief: 解析Get请求uri和请求参数
@ Author: woniu201
@ Created: 2019/11/26
@ Return:
************************************/
char *find_http_header(struct evhttp_request *req, struct evkeyvalq *params, const char *query_char)
{
if(req == NULL || params == NULL || query_char == NULL)
{
printf("line:%d, %s\n", __LINE__, "Input params is null.");
return NULL;
}

struct evhttp_uri *decoded = NULL;
char *query = NULL;
char *query_result = NULL;
const char *path;
const char *uri = evhttp_request_get_uri(req);//获取请求uri

if(uri == NULL)
{
printf("line:%d, evhttp_request_get_uri return null\n", __LINE__);
return NULL;
}
else
{
printf("line:%d, Got a GET request for <%s>\n",__LINE__, uri);
}

//解码uri
decoded = evhttp_uri_parse(uri);
if (!decoded)
{
printf("line:%d, It's not a good URI. Sending BADREQUEST\n", __LINE__);
evhttp_send_error(req, HTTP_BADREQUEST, 0);
return NULL;
}

//获取uri中的path部分
path = evhttp_uri_get_path(decoded);
if (path == NULL)
{
path = "/";
}
else
{
printf("line:%d, path is:%s\n", __LINE__, path);
}

//获取uri中的参数部分
query = (char*)evhttp_uri_get_query(decoded);
if(query == NULL)
{
printf("line:%d, evhttp_uri_get_query return null\n", __LINE__);
return NULL;
}

//查询指定参数的值
evhttp_parse_query_str(query, params);
query_result = (char*)evhttp_find_header(params, query_char);

return query_result;
}

/************************************
@ Brief: GET请求处理函数
@ Author: woniu201
@ Created: 2019/11/26
@ Return:
************************************/
void httpHandlerGetMsg(struct evhttp_request *req, void *arg)
{
if(req == NULL)
{
printf("line:%d, %s\n", __LINE__, "Input param req is null.");
return;
}

char *param1 = NULL;
char *param2 = NULL;

struct evkeyvalq sign_params = {0};

//获取url中param1参数
param1 = find_http_header(req, &sign_params, "param1");
if(param1 == NULL)
{
printf("line:%d, %s\n", __LINE__, "Request uri no param param1.");
}
else
{
printf("line:%d, Get Request Param: param1=[%s]\n", __LINE__, param1);
}

//获取url中param2参数
param2 = find_http_header(req, &sign_params, "param2");
if(param2 == NULL)
{
printf("line:%d, %s\n", __LINE__, "Request uri no param param2.");
}
else
{
printf("line:%d, Get Request Param: param1=[%s]\n", __LINE__, param2);
}
printf("\n");

//Http响应请求
struct evbuffer *retbuff = NULL;
retbuff = evbuffer_new();
if(retbuff == NULL)
{
printf("line:%d, %s\n", __LINE__, "retbuff is null.");
return;
}

evbuffer_add_printf(retbuff,"Receive get request SUCC!");
evhttp_send_reply(req,HTTP_OK,"Client",retbuff);
evbuffer_free(retbuff);
}

/************************************
@ Brief: POST请求处理函数
@ Author: woniu201
@ Created: 2019/11/26
@ Return:
************************************/
void http_handler_testpost_msg(struct evhttp_request *req,void *arg)
{
if(req == NULL)
{
printf("====line:%d,%s\n",__LINE__,"input param req is null.");
return;
}

char buf[BUF_MAX] = {0};
get_post_message(buf, req);//获取请求数据,一般是json格式的数据
if(buf == NULL)
{
printf("====line:%d,%s\n",__LINE__,"get_post_message return null.");
return;
}
else
{
//可以使用json库解析需要的数据
printf("====line:%d,request data:%s",__LINE__,buf);
}

//回响应
struct evbuffer *retbuff = NULL;
retbuff = evbuffer_new();
if(retbuff == NULL)
{
printf("====line:%d,%s\n",__LINE__,"retbuff is null.");
return;
}
evbuffer_add_printf(retbuff,"Receive get request SUCC!");
evhttp_send_reply(req,HTTP_OK,"Client",retbuff);
evbuffer_free(retbuff);
}

int main()
{

#ifdef WIN32
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
(void)WSAStartup(wVersionRequested, &wsaData);
#endif

struct evhttp *http_server = NULL;
short http_port = 8082;
char *http_addr = "0.0.0.0";

//初始化
event_init();
//启动http服务端
http_server = evhttp_start(http_addr,http_port);
if(http_server == NULL)
{
printf("====line:%d,%s\n",__LINE__,"http server start failed.");
return -1;
}

//设置请求超时时间(s)
evhttp_set_timeout(http_server,5);

//设置事件处理函数,evhttp_set_cb针对每一个事件(请求)注册一个处理函数,
//区别于evhttp_set_gencb函数,是对所有请求设置一个统一的处理函数
evhttp_set_cb(http_server,"/me/testpost",http_handler_testpost_msg,NULL);
evhttp_set_cb(http_server,"/me/testget",httpHandlerGetMsg,NULL);

//循环监听
event_dispatch();
//实际上不会释放,代码不会运行到这一步
evhttp_free(http_server);

return 0;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×