UDP 怎么使用EPOLL 监听接收
时间: 2024-03-23 07:43:27 浏览: 80
使用EPOLL监听UDP接收需要以下步骤:
1. 创建UDP套接字并绑定端口号
2. 创建epoll实例,将UDP套接字添加到epoll实例中
3. 调用epoll_wait()函数进行监听事件
4. 如果epoll_wait()返回UDP套接字有事件发生,则调用recvfrom()函数接收UDP数据包
以下是一个简单的示例代码:
```
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_EVENTS 10
int main() {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(8080);
bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
int epfd = epoll_create(MAX_EVENTS);
struct epoll_event event, events[MAX_EVENTS];
event.data.fd = sockfd;
event.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &event);
while (1) {
int n = epoll_wait(epfd, events, MAX_EVENTS, -1);
for (int i = 0; i < n; i++) {
if (events[i].data.fd == sockfd) {
char buffer[1024];
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_len);
printf("Received %d bytes from %s:%d\n", len, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
}
}
}
close(epfd);
close(sockfd);
return 0;
}
```
在这个示例代码中,我们创建了一个UDP套接字,并绑定了端口号8080。然后,我们创建了一个epoll实例,并将UDP套接字添加到epoll实例中。在主循环中,我们调用epoll_wait()函数进行监听事件,如果UDP套接字有事件发生(EPOLLIN),则调用recvfrom()函数接收UDP数据包。
阅读全文