代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <event2/buffer.h>
#include <event2/listener.h>
void * api_index(struct evhttp_request * ev_request, void * arg)
{
char buf[1024];
//sprintf(buf, “
sprintf(buf, “hello world!”);//网页根目录显示的内容
struct evbuffer* evbuff = evbuffer_new();
evbuffer_add_printf(evbuff,“%s”,buf);
evhttp_send_reply(ev_request, HTTP_OK, NULL, evbuff);
evbuffer_free(evbuff);
}
int main(int agrc, const char * argv[])
{
const char* ip = “127.0.0.1”;
int port = 6868;
struct event_config * evt_config = event_config_new();//默认配置
struct event_base * base = event_base_new_with_config(evt_config);//使用默认配置创造event_base
struct evhttp* http = evhttp_new(base);//创造http服务器,处理http请求
evhttp_set_default_content_type(http,"text/html/ charset=utf/8");//默认html格式回复客户端
evhttp_set_timeout(http, 30);//tcp的sml时间为30毫秒
//设置url的回调函数
evhttp_set_cb(http,"/",(void *)api_index, NULL);
//evhttp_set_cb(http,"/api/health",api_health,this);
evhttp_bind_socket(http,ip,port); //绑定端口和ip地址
event_base_dispatch(base); //事件分发循环
event_base_free(base);
evhttp_free(http);
event_config_free(evt_config);
}