http服务端实现
libevent的开源库自行在github下载,然后根据交叉编译工具进行编译
编译参数仅供参考,如果需要开启ssl,自行查阅资料如何加上openssl一起编译编译,本文只针对简单的http server框架的实现提供代码
./configure --prefix=$(pwd)/…/output --host=aarch64-linux-gnu --disable-openssl CFLAGS=-fPIC
make clean && make && make install
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <event.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <event2/http_compat.h>
#include <event2/buffer_compat.h>
#include <event2/util.h>
#include <event2/event_compat.h>
#include <event2/buffer.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/http.h>
#include <event2/http_struct.h>
//#include "libevent_http.h"
#define COMMON_SUCCESS_MSG "{\"msg\":\"success\", \"code\":200}"
#define COMMON_TEST_MSG "{\"msg\":\"This is a test!\", \"code\":200}"
#define COMMON_FAIL_MSG "{\"msg\":\"bad requst\", \"code\":500}"
void httpServer_CommonDel(struct evhttp_request *req, void *arg)
{
int RecvDataLen = 0;
char lengthBuffer[16]={0};
char szData[100] = {0};
char *pcRecvData = NULL;
/* 只支持POST GET两种请求 */
if ((req->type != EVHTTP_REQ_POST) && (req->type != EVHTTP_REQ_GET))
{
printf("not support method[%d]\n", req->type);
return;
}
/*获取POST方法的数据*/
RecvDataLen = EVBUFFER_LENGTH(req->input_buffer);
pcRecvData = (char *) EVBUFFER_DATA(req->input_buffer);
printf("%s get post_data, len =%d uri:%s\n",__FUNCTION__, RecvDataLen, req->uri);
printf("RCV:\n%s\n",pcRecvData);
/* 自行添加对应uri的处理 */
if (NULL != strstr(req->uri, "/test"))
{
strncpy(szData, COMMON_TEST_MSG, sizeof(szData) - 1);
}
else
{
strncpy(szData, COMMON_SUCCESS_MSG, sizeof(szData) - 1);
}
//HTTP header
evutil_snprintf(lengthBuffer, sizeof(lengthBuffer) - 1, "%lu", strlen(szData));
evhttp_add_header(req->output_headers, "Content-Type", "application/json; charset=UTF-8");
evhttp_add_header(req->output_headers, "Content-Length",lengthBuffer);
evhttp_add_header(req->output_headers, "Connection", "close");
struct evbuffer *buf = evhttp_request_get_output_buffer(req);
evbuffer_add(buf, szData, strlen(szData));
//将封装好的evbuffer 发送给客户端
evhttp_send_reply(req, 200, "OK", buf);
}
int main(int argc, char **argv)
{
struct evhttp *pstHttpEV = NULL;
//初始化event_init
event_init();
pstHttpEV = evhttp_start("0.0.0.0", 7689);
evhttp_set_timeout(pstHttpEV, 30);
/*通用处理回调函数指定*/
evhttp_set_gencb(pstHttpEV, httpServer_CommonDel, NULL);
//循环处理events
event_dispatch();
evhttp_free(pstHttpEV);
return 0;
}