一段简单的epoll测试例子,编译运行后可以直接用浏览器访问localhost来测试。
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 14 char content[] = " Hello TEST";15 char response[512];16 17 int18 rep_err(char *err)19 {20 fprintf(stderr, "%s\n", err);21 perror("ERROR");22 exit(-1);23 }24 25 int26 setnonblock(int fd)27 {28 if(fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK) < 0)29 return -1;30 return 0;31 }32 33 34 int35 main(int argc, char *argv[])36 {37 struct sockaddr_in servaddr, cliaddr;38 socklen_t clilen;39 uint32_t listenfd, connfd, efd, err, n, i;40 char buffer[1024];41 struct epoll_event ev, events[256];42 43 signal(SIGPIPE, SIG_IGN);44 45 sprintf(response, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %zd\r\n\r\n%s", strlen(content), content);46 47 if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) <= 0)48 rep_err("create socket failed");49 50 bzero(&servaddr, sizeof(servaddr));51 servaddr.sin_family = AF_INET;52 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);53 servaddr.sin_port = htons(80);54 55 if((err = bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) != 0)56 rep_err("bind host failed");57 58 if((err = listen(listenfd, 6)) != 0)59 rep_err("listen host failed");60 61 setnonblock(listenfd);62 63 efd = epoll_create(256);64 ev.data.fd = listenfd;65 ev.events = EPOLLIN | EPOLLET;66 epoll_ctl(efd, EPOLL_CTL_ADD, listenfd, &ev);67 68 for(;;)69 {70 n = epoll_wait(efd, events, 256, -1);71 for(i = 0; i < n; ++i)72 { 73 if(events[i].data.fd == listenfd)74 {75 clilen = sizeof(cliaddr);76 if((connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen)) <= 0)77 rep_err("accept connect failed");78 printf("CONNECT FROM %s , PORT: %d\n", 79 inet_ntop(AF_INET, &cliaddr.sin_addr, buffer, sizeof(buffer)),80 ntohs(cliaddr.sin_port));81 setnonblock(connfd);82 ev.data.fd = connfd;83 ev.events = EPOLLIN |EPOLLET;84 epoll_ctl(efd, EPOLL_CTL_ADD, connfd, &ev);85 }86 else87 {88 write(events[i].data.fd, response, strlen(response));89 write(events[i].data.fd, content, strlen(content));90 }91 }92 }93 return 0;94 }
posted on 2013-04-08 19:56 阅读( ...) 评论( ...)