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 119 120
| #include <iostream> #include <sys/socket.h> #include <sys/epoll.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #define MAXLINE 10 #define OPEN_MAX 100 #define LISTENQ 20 #define SERV_PORT 5555 #define INFTIM 1000
void setnonblocking(int sock) { int opts; opts = fcntl(sock, F_GETFL); if(opts < 0) { perror("fcntl(sock, GETFL)"); exit(1); } opts = opts | O_NONBLOCK; if(fcntl(sock, F_SETFL, opts) < 0) { perror("fcntl(sock,SETFL,opts)"); exit(1); } }
int main() { int i, maxi, listenfd, connfd, sockfd, epfd, nfds; ssize_t n; char line[MAXLINE]; socklen_t clilen; struct epoll_event ev,events[20]; epfd = epoll_create(256); struct sockaddr_in clientaddr; struct sockaddr_in serveraddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); setnonblocking(listenfd); ev.data.fd = listenfd; ev.events = EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev); bzero(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; char* local_addr = "200.200.200.204"; inet_aton(local_addr, &(serveraddr.sin_addr)); serveraddr.sin_port = htons(SERV_PORT); bind(listenfd,(sockaddr *)&serveraddr, sizeof(serveraddr)); listen(listenfd, LISTENQ);
maxi = 0; for( ; ; ) { nfds = epoll_wait(epfd, events, 20, 500); for(i = 0; i < nfds; ++i) { if(events[i].data.fd == listenfd) { connfd = accept(listenfd, (sockaddr *)&clientaddr, &clilen); if(connfd < 0) { perror("connfd<0"); exit(1); } setnonblocking(connfd); char* str = inet_ntoa(clientaddr.sin_addr); std::cout << "connect from " << str <<std::endl; ev.data.fd=connfd; ev.events=EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev); } else if(events[i].events&EPOLLIN) { if ( (sockfd = events[i].data.fd) < 0) { continue; } if ( (n = read(sockfd, line, MAXLINE)) < 0) { if (errno == ECONNRESET) { close(sockfd); events[i].data.fd = -1; } else { std::cout<<"readline error"<<std::endl; } } else if (n == 0) { close(sockfd); events[i].data.fd = -1; } ev.data.fd=sockfd; ev.events=EPOLLOUT | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev); } else if(events[i].events&EPOLLOUT) { sockfd = events[i].data.fd; write(sockfd, line, n); ev.data.fd = sockfd; ev.events = EPOLLIN | EPOLLET; epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev); } } } }
|