epoll 实现client
时间: 2023-12-12 20:03:43 浏览: 82
epoll_serverANDclient
下面是使用 epoll 实现的一个简单的 TCP 客户端:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <errno.h>
#define MAX_EVENTS 10
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <ip> <port>\n", argv[0]);
exit(1);
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(1);
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(1);
}
int epollfd = epoll_create(MAX_EVENTS);
if (epollfd == -1) {
perror("epoll_create");
exit(1);
}
struct epoll_event ev, events[MAX_EVENTS];
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.fd = sockfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
perror("epoll_ctl");
exit(1);
}
char buf[BUF_SIZE];
while (1) {
int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (nfds == -1) {
if (errno == EINTR) {
continue;
}
perror("epoll_wait");
exit(1);
}
for (int i = 0; i < nfds; ++i) {
if (events[i].data.fd == sockfd) {
int n = read(sockfd, buf, BUF_SIZE);
if (n == -1) {
perror("read");
exit(1);
} else if (n == 0) {
printf("Server closed connection\n");
close(sockfd);
exit(0);
} else {
buf[n] = '\0';
printf("Received message: %s", buf);
}
}
}
}
return 0;
}
```
首先创建了一个 socket,并连接到指定的服务器。然后创建一个 epoll 实例,将 socket 加入到 epoll 中,并设置监听的事件类型为可读。之后不断循环调用 epoll_wait 等待事件的发生,如果是 socket 的可读事件,则读取数据并打印。
阅读全文