Libevent 是一个异步IO的c语言网络库,带了一个简单的http支持
用c/c++写http server,也没有比这个更方便的做法了
但是比起php/ruby/python来,编程还是很繁琐,各种不方便,唉,写c语言的快绝种了
Libevent 写了一本很不错的文档,linux下写网络程序必看 Fast portable non-blocking network programming with Libevent
#include <event.h>
#include <evhttp.h>
#define BUF_MAX 1024*16
static char _buf[ BUF_MAX ];
void post_handler(struct evhttp_request *req, void *arg)
{
std::string out;
size_t post_size = EVBUFFER_LENGTH(req->input_buffer);
printf("len = %dn", post_size);
if (post_size > 0 )
{
size_t copy_len = post_size > BUF_MAX ? BUF_MAX : post_size;
memcpy (_buf, EVBUFFER_DATA(req->input_buffer), copy_len);
out.assign(_buf, copy_len);
}
// process posted data
struct evbuffer *pe = evbuffer_new();
evbuffer_add(pe, out.data(), out.size());
evhttp_send_reply(req, HTTP_OK, "OK", pe);
evbuffer_free(pe);
}
evhttp_set_cb(http, "/post", post_handler, NULL);
- 核心就在于
EVBUFFER_LENGTH和EVBUFFER_DATA两个宏,这是在event.h中定义的,得到buffer的头指针和长度,memcpy出来,随便处理 - 这是Libevent 2.0.x 才支持的功能
- 测试的时候用
curl 网址 -d "test"或者curl 网址 --data-binary @"/etc/profile"提交数据 - 这种post 提是直接post,并不是urlencode的方式
转载请注明:爱开源 » libevent 处理 http post 请求