libevent 高并发http服务器代码
时间: 2023-08-18 17:05:21 浏览: 100
下面是一个基于libevent的高并发HTTP服务器的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <event.h>
#define SERVER_PORT 8080
#define MAX_CLIENTS 64
void on_accept(int fd, short event, void *arg) {
int client_fd = accept(fd, NULL, NULL);
if (client_fd < 0) {
perror("accept");
return;
}
printf("Accepted connection from client %d\n", client_fd);
struct event_base *base = (struct event_base *)arg;
struct bufferevent *bev = bufferevent_socket_new(base, client_fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, NULL, NULL, NULL, NULL);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
void on_request(struct bufferevent *bev, void *arg) {
char buffer[1024];
int n;
while ((n = bufferevent_read(bev, buffer, sizeof(buffer))) > 0) {
printf("Received %d bytes from client %d\n", n, bufferevent_getfd(bev));
bufferevent_write(bev, buffer, n);
}
}
int main(int argc, char *argv[]) {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("socket");
exit(1);
}
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(SERVER_PORT);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
exit(1);
}
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(1);
}
printf("Server is listening on port %d\n", SERVER_PORT);
struct event_base *base = event_base_new();
struct event *server_event = event_new(base, server_fd, EV_READ | EV_PERSIST, on_accept, base);
event_add(server_event, NULL);
event_base_dispatch(base);
return 0;
}
```
这个程序使用了libevent库来实现一个简单的高并发HTTP服务器,它可以同时处理多个客户端连接。当有新的客户端连接时,服务器会使用bufferevent_socket_new函数创建一个新的bufferevent来处理该连接。当客户端发送数据时,服务器会使用bufferevent_read函数来读取数据,并使用bufferevent_write函数将数据发送回客户端。
阅读全文