摘要:“,__LINE_);return;}else{size_tcopy_len=post_size˃BUF_MAX?BUF_MAX:post_size;printf(”===行:%d,postlen:%d,copy_len:%d“,__LINE__,post_size,copy_en);memcpy(BUF,evbuffer_pullup(req-˃input_buffer,-1),copy_lun);BUF[post_size]='
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "evhttp.h"
#include "event.h"
#include "event2/http.h"
#include "event2/event.h"
#include "event2/buffer.h"
#include "event2/bufferevent.h"
#include "event2/bufferevent_compat.h"
#include "event2/http_struct.h"
#include "event2/http_compat.h"
#include "event2/util.h"
#include "event2/listener.h"
int main()
{
struct evhttp *http_server = NULL;
short http_port = 8081;
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
", __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, "/post", http_handler_testpost_msg, NULL);
evhttp_set_cb(http_server, "/get", http_handler_testget_msg, NULL);
//循环监听
event_dispatch();
//实际上不会释放,代码不会运行到这一步
evhttp_free(http_server);
return 0;
}
//解析post请求数据
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
", __LINE__, post_size);
if (post_size <= 0)
{
printf("====line:%d,post msg is empty!
", __LINE__);
return;
}
else
{
size_t copy_len = post_size > BUF_MAX ? BUF_MAX : post_size;
printf("====line:%d,post len:%d, copy_len:%d
", __LINE__, post_size, copy_len);
memcpy(buf, evbuffer_pullup(req->input_buffer, -1), copy_len);
buf[post_size] = '