日期:2014-05-16 浏览次数:20778 次
int main(int argc, char *argv) { int i, maxi, maxfd, listenfd, connfd, sockfd; int nready, client[FD_SETSIZE]; ssize_t n; fd_set rest, allrest; char buf[512]; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(listenfd, 5); maxfd = listenfd; /* 初始化 */ maxi = -1; for (i = 0; i < FD_SETSIZE; i++) { client[i] = -1; } FD_ZERO(&allrest); FD_SET(listenfd, &allrest); /* 告诉内核,我们需要对哪些描述字进行测试 */ for (; ;) { rest = allrest; nready = select(maxfd+1, &rest, NULL, NULL, NULL); if (FD_ISSET(listenfd, &rest)) /* 返回后, rest结构中的内容被重写,任何未就绪的描述字被置为0 */ { clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); for (i=0; i < FD_SETSIZE; i++) { if (client[i] < 0) { client[i] = connfd; break; } } if (i == FD_SETSIZE) return -1; FD_SET(connfd, &allrest); if (connfd > maxfd) maxfd = connfd; if (i > maxi) maxi = i; if (--nready <= 0) { continue; } } for (i = 0; i < maxi; i++) { printf("44444444\n"); if ((sockfd = client[i]) < 0) continue; if (FD_ISSET(sockfd, &rest)) { printf("55555555555\n"); if ((n = read(sockfd, buf, 512)) == 0) { close(sockfd); FD_CLR(sockfd, &allrest); client[i] = -1; } else { write(sockfd, buf, n); } if (--nready <= 0) break; } } } }