代码:
1 /* 2 * g++ -o stress_test ./stress_test.cpp 3 */ 4 5 #include <stdlib.h> 6 #include <stdio.h> 7 #include <string.h> 8 #include <errno.h> 9 10 #include <unistd.h> 11 #include <sys/types.h> 12 #include <sys/epoll.h> 13 #include <fcntl.h> 14 #include <sys/socket.h> 15 #include <netinet/in.h> 16 #include <arpa/inet.h> 17 18 static const char *request = "GET / HTTP/1.1 Host: 192.168.1.5 Connection: keep-alive "; 19 20 int setnonblocking(int fd) 21 { 22 int old_option = fcntl(fd, F_GETFL); 23 int new_option = old_option | O_NONBLOCK; 24 fcntl(fd, F_SETFL, new_option); 25 26 return old_option; 27 } 28 29 int add_fd(int epoll_fd, int fd) 30 { 31 struct epoll_event event; 32 event.events = EPOLLOUT | EPOLLET | EPOLLERR; 33 event.data.fd = fd; 34 epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event); 35 setnonblocking(fd); 36 } 37 38 bool write_nbytes(int sockfd, const char *buffer, int len) 39 { 40 int bytes_write = 0; 41 printf("write out %d bytes to socket %d ", len, sockfd); 42 while(1) 43 { 44 bytes_write = send(sockfd, buffer, len, 0); 45 if (bytes_write == -1) 46 { 47 printf("send failed, errno[%d], error[%s] ", errno, strerror(errno)); 48 return false; 49 } 50 else if (bytes_write == 0) 51 { 52 printf("send 0 bytes "); 53 return false; 54 } 55 56 len -= bytes_write; 57 buffer = buffer + bytes_write; 58 if (len <= 0) 59 { 60 return true; 61 } 62 } 63 } 64 65 bool read_once(int sockfd, char *buffer, int len) 66 { 67 int bytes_read = 0; 68 memset(buffer, '