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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <netinet/in.h> #include <ctype.h> #include <poll.h> //poll头文件
#define MAXSIZE 1024 #define IP_ADDR "127.0.0.1" #define IP_PORT 8888
int main() { int i_listenfd, i_connfd; struct sockaddr_in st_sersock; char msg[MAXSIZE]; int nrecvSize = 0; int index = 0; struct pollfd pofds[MAXSIZE];
for(n : pofds) { n.fd = -1; }
if((i_listenfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0) { printf("socket Error: %s (errno: %d)\n", strerror(errno), errno); exit(0); }
memset(&st_sersock, 0, sizeof(st_sersock)); st_sersock.sin_family = AF_INET; st_sersock.sin_addr.s_addr = htonl(INADDR_ANY); st_sersock.sin_port = htons(IP_PORT);
if(bind(i_listenfd,(struct sockaddr*)&st_sersock, sizeof(st_sersock)) < 0) { printf("bind Error: %s (errno: %d)\n", strerror(errno), errno); exit(0); }
if(listen(i_listenfd, 20) < 0) { printf("listen Error: %s (errno: %d)\n", strerror(errno), errno); exit(0); } printf("listen fd: %d\n", i_listenfd);
pofds[index].fd = i_listenfd; pofds[index].events = POLLIN; printf("======waiting for client's request======\n"); while(1) { int nCount = poll(pofds, index+1, -1); printf("----------poll监听到可读事件计数:%d\n",nCount);
for(int i = 0; i < MAXSIZE; i++) { if(nCount == 0) { break; } if(!(pofds[i].revents & POLLIN)) { continue; } printf("----------即将处理监听到的 pofds[%d]: %d\n", i, pofds[i].fd); nCount--; if(pofds[i].fd == i_listenfd) { if((i_connfd = accept(i_listenfd, (struct sockaddr*)NULL, NULL)) < 0) { printf("accept Error: %s (errno: %d)\n", strerror(errno), errno); } else { printf("Client[%d], welcome!\n", i_connfd); }
for(int n = 0; n < MAXSIZE; n++) { if(pofds[n].fd == -1) { pofds[n].fd = i_connfd; pofds[n].events = POLLIN; index < n ? index = n : true ; printf("将新客户端fd加入数组中. fd:%d, index:%d\n", pofds[n].fd, index); break; } } } else { memset(msg, 0 ,sizeof(msg)); if((nrecvSize = read(pofds[i].fd, msg, MAXSIZE)) < 0) { printf("accept Error: %s (errno: %d)\n", strerror(errno), errno); continue; } else if( nrecvSize == 0) { printf("client has disconnected!\n"); if(index == i) { index--; } pofds[i].fd = -1; close(pofds[i].fd); continue; } else { printf("recvMsg:%s", msg); for(int i=0; msg[i] != '\0'; i++) { msg[i] = toupper(msg[i]); } if(write(pofds[i].fd, msg, strlen(msg)+1) < 0) { printf("accept Error: %s (errno: %d)\n", strerror(errno), errno); }
} } } } close(i_listenfd);
return 0; }
|