libevent实现的http服务器代码
时间: 2023-09-29 12:07:22 浏览: 120
以下是基于libevent实现的简单HTTP服务器代码,仅供参考:
```c
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
static void http_handler(struct evhttp_request *req, void *arg) {
struct evbuffer *buf;
const char *uri = evhttp_request_get_uri(req);
buf = evbuffer_new();
if (!buf) {
perror("failed to create response buffer");
return;
}
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/plain");
if (evhttp_request_get_command(req) == EVHTTP_REQ_GET) {
evbuffer_add_printf(buf, "Received a GET request for %s\n", uri);
} else if (evhttp_request_get_command(req) == EVHTTP_REQ_POST) {
evbuffer_add_printf(buf, "Received a POST request for %s\n", uri);
} else {
evbuffer_add_printf(buf, "Unsupported HTTP method\n");
}
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
int main(int argc, char **argv) {
struct event_base *base;
struct evhttp *http;
struct evhttp_bound_socket *handle;
base = event_base_new();
if (!base) {
perror("failed to create event base");
return 1;
}
http = evhttp_new(base);
if (!http) {
perror("failed to create http server");
return 1;
}
evhttp_set_cb(http, "/", http_handler, NULL);
handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", 8080);
if (!handle) {
perror("failed to bind socket");
return 1;
}
event_base_dispatch(base);
evhttp_free(http);
event_base_free(base);
return 0;
}
```
以上代码实现了一个简单的HTTP服务器,监听本机的8080端口,当有HTTP请求到来时,根据请求方法(GET或POST)返回相应的响应。其中,libevent提供了evhttp库来实现HTTP协议的处理,evhttp_request_get_uri()获取请求的URI,evhttp_request_get_output_headers()获取请求的响应头,evhttp_add_header()设置响应头,evhttp_request_get_command()获取请求的方法类型(GET或POST),evbuffer_add_printf()将格式化的字符串添加到响应体中,evhttp_send_reply()发送响应,evbuffer_free()释放响应体的内存。
阅读全文