libevent http演示示例
时间: 2024-06-10 09:03:02 浏览: 80
libevent是一个事件驱动的网络库,支持多种I/O复用机制,如select、poll、epoll等,能够在高并发的网络环境下提供高效的网络通信。下面是一个简单的libevent http演示示例:
```c
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
void http_handler(struct evhttp_request *req, void *arg) {
struct evbuffer *buf;
buf = evbuffer_new();
evbuffer_add_printf(buf, "Hello World!");
evhttp_send_reply(req, HTTP_OK, "OK", buf);
}
int main() {
struct event_base *base;
struct evhttp *http;
base = event_base_new();
http = evhttp_new(base);
evhttp_bind_socket(http, "0.0.0.0", 8080);
evhttp_set_cb(http, "/", http_handler, NULL);
event_base_dispatch(base);
return 0;
}
```
这个示例创建了一个HTTP服务,监听本地8080端口,当收到客户端的HTTP请求时,回复"Hello World!"。可以使用curl命令测试一下:
```
curl http://localhost:8080
```
输出结果为:
```
Hello World!
```
阅读全文