#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
// 回调函数,处理接收到的UDP数据包
static void udp_read_cb(struct bufferevent* bev, void* ctx) {
struct evbuffer* input = bufferevent_get_input(bev);
struct evbuffer* output = bufferevent_get_output(bev);
// 将接收到的UDP数据包写回客户端
evbuffer_add_buffer(output, input);
}
// 回调函数,处理UDP错误事件
static void udp_event_cb(struct bufferevent* bev, short events, void* ctx) {
if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
fprintf(stderr, "UDP connection closed or encountered an error.\n");
// 关闭连接
bufferevent_free(bev);
}
}
// 回调函数,处理UDP连接请求
static void udp_conn_cb(evutil_socket_t fd, short events, void* arg) {
struct event_base* base = (struct event_base*)arg;
// 创建一个UDP bufferevent
struct bufferevent* bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_UDP);
if (!bev) {
fprintf(stderr, "Error constructing bufferevent!");
event_base_loopbreak(base);
return;
}
// 设置回调函数,处理读取和错误事件
bufferevent_setcb(bev, udp_read_cb, NULL, udp_event_cb, NULL);
// 启用读取事件
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
int main() {
// 初始化libevent
struct event_base* base = event_base_new();
if (!base) {
fprintf(stderr, "Could not initialize libevent!\n");
return 1;
}
// 创建一个UDP监听器,监听在本地8888端口
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
evutil_socket_t udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (bind(udp_socket, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
perror("bind");
return 1;
}
// 创建UDP连接监听事件
struct event* udp_event = event_new(base, udp_socket, EV_READ | EV_PERSIST, udp_conn_cb, base);
event_add(udp_event, NULL);
// 进入事件循环
event_base_dispatch(base);
// 清理资源
event_free(udp_event);
event_base_free(base);
return 0;
}