c语言epoll 客户端代码
时间: 2023-11-10 22:03:05 浏览: 112
C语言中使用epoll机制编写客户端代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#define MAX_EVENTS 100
#define MAX_BUF_SIZE 1024
int main(int argc, char** argv) {
int sockfd, epollfd;
struct epoll_event event, events[MAX_EVENTS];
// 创建socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
if (inet_pton(AF_INET, "127.0.0.1", &(server_addr.sin_addr)) <= 0) {
perror("invalid address");
exit(EXIT_FAILURE);
}
// 连接服务器
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("connection failed");
exit(EXIT_FAILURE);
}
// 创建epoll实例
if ((epollfd = epoll_create1(0)) < 0) {
perror("epoll creation failed");
exit(EXIT_FAILURE);
}
// 设置监听事件
event.events = EPOLLIN;
event.data.fd = sockfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &event) < 0) {
perror("epoll control failed");
exit(EXIT_FAILURE);
}
char buf[MAX_BUF_SIZE];
while (1) {
int num_events = epoll_wait(epollfd, events, MAX_EVENTS, -1);
for (int i = 0; i < num_events; i++) {
if (events[i].data.fd == sockfd) {
// 从服务器接收数据
memset(buf, 0, sizeof(buf));
ssize_t recv_len = recv(sockfd, buf, sizeof(buf), 0);
if (recv_len < 0) {
perror("receive data failed");
exit(EXIT_FAILURE);
} else if (recv_len == 0) {
printf("Connection closed by server\n");
exit(EXIT_SUCCESS);
} else {
printf("Received message from server: %s", buf);
}
}
}
}
close(sockfd);
close(epollfd);
return 0;
}
```
以上代码实现了一个简单的epoll客户端,将连接到服务器的socket加入到epoll事件中进行监听。当有事件触发时,通过recv函数接收服务器发送的数据,并打印到控制台上。同时,代码还对错误情况进行了处理,比如socket创建失败、连接失败等。
阅读全文