#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <string.h>
#define MAX_EVENTS 10
int main() {
int sockfd;
struct sockaddr_in server_addr, client_addr;
int epoll_fd;
struct epoll_event events[MAX_EVENTS];
const int timeout_ms = 5000; // 超时时间设定为5秒
char buffer[1024];
// 创建UDP socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// 设置socket地址和端口
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// 绑定socket
if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to bind socket");
exit(EXIT_FAILURE);
}
// 创建epoll实例
epoll_fd = epoll_create1(0);
if (epoll_fd == -1) {
perror("Failed to create epoll instance");
exit(EXIT_FAILURE);
}
// 添加socket到epoll实例中
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = sockfd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &event) == -1) {
perror("Failed to add socket to epoll instance");
exit(EXIT_FAILURE);
}
while (1) {
int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, timeout_ms);
if (num_events == -1) {
perror("epoll_wait error");
break;
} else if (num_events == 0) {
printf("Timeout occurred\n");
continue;
}
for (int i = 0; i < num_events; ++i) {
if (events[i].data.fd == sockfd) {
socklen_t addr_len = sizeof(client_addr);
ssize_t recv_len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &addr_len);
if (recv_len == -1) {
perror("Failed to receive data");
} else {
buffer[recv_len] = '\0';
printf("Received data: %s\n", buffer);
}
}
}
}
// 关闭socket和epoll实例
close(sockfd);
close(epoll_fd);
return 0;
}
上述代码创建了一个UDP socket,并将其绑定到本地地址和端口上。然后使用epoll创建了一个epoll实例,并将socket添加进去进行监听。在epoll_wait的循环中,等待事件发生,如果超时则进行超时处理逻辑,否则接收UDP数据并进行处理。
请注意,上述示例只是一个简单的实现,对于真实场景,可能需要进行错误处理、异常情况处理等更完善的代码编写。