封装libevent的c++调用库
时间: 2023-09-11 20:04:14 浏览: 70
封装libevent的C调用库,可以让开发人员更方便地使用libevent来开发网络应用程序。以下是一个简单的例子,演示如何使用封装库来创建一个简单的TCP服务器:
```c
#include <stdio.h>
#include "event.h"
void on_accept(evutil_socket_t fd, short events, void* arg)
{
struct event_base* base = (struct event_base*)arg;
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_fd = accept(fd, (struct sockaddr*)&client_addr, &client_len);
if (client_fd < 0) {
perror("accept failed");
return;
}
printf("client connected: %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
struct event* client_event = event_new(base, client_fd, EV_READ | EV_PERSIST, on_recv, base);
event_add(client_event, NULL);
}
void on_recv(evutil_socket_t fd, short events, void* arg)
{
struct event_base* base = (struct event_base*)arg;
char buf[1024];
int n = recv(fd, buf, sizeof(buf), 0);
if (n < 0) {
perror("recv failed");
return;
}
if (n == 0) {
printf("client disconnected\n");
event_free((struct event*)arg);
close(fd);
return;
}
printf("received %d bytes: %.*s\n", n, n, buf);
send(fd, buf, n, 0);
}
int main()
{
struct event_base* base = event_base_new();
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("socket failed");
return 1;
}
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(12345);
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
return 1;
}
if (listen(server_fd, 10) < 0) {
perror("listen failed");
return 1;
}
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);
event_base_free(base);
return 0;
}
```
在上面的例子中,我们定义了两个回调函数:on_accept函数在有新的客户端连接时被调用,on_recv函数在有客户端发送数据时被调用。在main函数中,我们创建了一个event_base对象,并使用event_new函数创建了一个server_event,用于监听server_fd。当有新的客户端连接时,on_accept函数会被调用,并使用event_new函数创建一个client_event,用于监听client_fd。当有数据到达时,on_recv函数会被调用。最后,我们使用event_base_dispatch函数进入事件循环,等待事件的发生。
阅读全文