1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netinet/tcp.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/poll.h> #include <unistd.h> #define BUFFER_LENGTH 1024 #define POLL_SIZE 1024 #define EPOLL_SIZE 1024
int main(int argc, char *argv[]) { if (argc < 2) { printf("Paramter Error\n"); return -1; } int port = atoi(argv[1]);
int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); return -1; }
struct sockaddr_in addr; memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { perror("bind"); return 2; }
if (listen(sockfd, 5) < 0) { perror("listen"); return 3; } int epoll_fd = epoll_create(EPOLL_SIZE); struct epoll_event ev, events[EPOLL_SIZE] = {0}; ev.events = EPOLLIN; ev.data.fd = sockfd; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &ev); while (1) { int nready = epoll_wait(epoll_fd, events, EPOLL_SIZE, -1); if (nready == -1) { printf("epoll_wait\n"); break; } int i = 0; for (i = 0; i < nready; i++) { if (events[i].data.fd == sockfd) { struct sockaddr_in client_addr; memset(&client_addr, 0, sizeof(struct sockaddr_in)); socklen_t client_len = sizeof(client_addr);
int clientfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len); if (clientfd <= 0) continue;
char str[INET_ADDRSTRLEN] = {0}; printf("recvived from %s at port %d, sockfd:%d, clientfd:%d\n", inet_ntop(AF_INET, &client_addr.sin_addr, str, sizeof(str)), ntohs(client_addr.sin_port), sockfd, clientfd);
ev.events = EPOLLIN; ev.data.fd = clientfd; epoll_ctl(epoll_fd, EPOLL_CTL_ADD, clientfd, &ev); } else { int clientfd = events[i].data.fd;
char buffer[BUFFER_LENGTH] = {0}; int ret = recv(clientfd, buffer, 5, 0); if (ret < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { printf("read all data"); continue; } close(clientfd); ev.events = EPOLLIN | EPOLLET; ev.data.fd = clientfd; epoll_ctl(epoll_fd, EPOLL_CTL_DEL, clientfd, &ev); } else if (ret == 0) { printf(" disconnect %d\n", clientfd); close(clientfd);
ev.events = EPOLLIN; ev.data.fd = clientfd; epoll_ctl(epoll_fd, EPOLL_CTL_DEL, clientfd, &ev);
break; } else { printf("Recv: %s, %d Bytes\n", buffer, ret); } } } } return 0; }
|