#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <fcntl.h> #include <pthread.h> #include <unistd.h> #include <sys/epoll.h> #include <string.h> #define BUFFER_LENGTH 128 #define EVENTS_LENGTH 128 char rbuffer[BUFFER_LENGTH] = {0}; char wbuffer[BUFFER_LENGTH] = {0}; int main() { int listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd == -1) return -1; struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(9999); if (-1 == bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) { return -2; } #if 0 //nonblock int flag = fcntl(listenfd, F_GETFL, 0); flag |= O_NONBLOCK; fcntl(listenfd, F_SETFL, flag); #endif listen(listenfd, 10); int epfd = epoll_create(1); struct epoll_event ev, events[EVENTS_LENGTH]; ev.events = EPOLLIN; ev.data.fd = listenfd; epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev); //printf("fd: %d\n", epfd); while (1) { int nready = epoll_wait(epfd, events, EVENTS_LENGTH, -1); //printf("nready: %d\n", nready); for (int i = 0; i < nready; i++) { int clientfd = events[i].data.fd; if (listenfd == clientfd) {//accept struct sockaddr_in client; socklen_t len = sizeof(client); int connfd = accept(listenfd, (struct sockaddr*)&client, &len); printf("accept: %d\n", connfd); //默认水平触发 ev.events = EPOLLIN/* | EPOLLET*/; ev.data.fd = connfd; epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev); } else if (events[i].events & EPOLLIN){//clientfd int n = recv(clientfd, rbuffer, BUFFER_LENGTH, 0); if (n > 0) { rbuffer[n] = '\0'; printf("recv: %s, length = %d\n", rbuffer, n); memcpy(wbuffer, rbuffer, BUFFER_LENGTH); ev.events = EPOLLOUT; ev.data.fd = clientfd; epoll_ctl(epfd, EPOLL_CTL_MOD, clientfd, &ev); } } else if (events[i].events & EPOLLOUT) { send(clientfd, wbuffer, BUFFER_LENGTH, 0); ev.events = EPOLLIN; ev.data.fd = clientfd; epoll_ctl(epfd, EPOLL_CTL_MOD, clientfd, &ev); } } } return 0; }