1 #include "apue.h" 2 3 int main(int argc, char *argv[]) 4 { 5 int i,maxi,maxfd,listenfd,connfd,sockfd; 6 int nready,client[FD_SETSIZE]; 7 ssize_t n; 8 fd_set rset,allset; 9 char buf[maxlen]; 10 socklen_t clilen; 11 struct sockaddr_in cliaddr,servaddr; 12 listenfd=socket(AF_INET,SOCK_STREAM,0); 13 bzero(&servaddr,sizeof(servaddr)); 14 servaddr.sin_family=AF_INET; 15 servaddr.sin_addr.s_addr=htonl(INADDR_ANY); 16 servaddr,sin_port=htons(8888); 17 bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); 18 maxfd=listenfd; 19 listen(listenfd,10); 20 maxi=-1; 21 memset(client,sizeof(client),-1); 22 FD_ZERO(allset); 23 FD_SET(listenfd,&allset); 24 /**************************************************/ 25 while(1) 26 { 27 rest=allset; 28 nready=select(maxfd+1,&rset,NULL,NULL,NULL); 29 if(FD_ISSET(listenfd,&rset)) 30 { 31 clilen=sizeof(cliaddr); 32 connfd=accept(listenfd,(SA*)&cliaddr,&clilen); 33 for(i=0;i<FD_SETSIZE;i++) 34 { 35 if(client[i]==-1) 36 { 37 client[i]=connfd; 38 } 39 } 40 if(i==FD_SETSIZE){perror("too many client!")} 41 FD_SET(connfd,&allset); 42 if(connfd>maxfd){maxfd=connfd;} 43 if(i>maxi){maxi=i;} 44 if(--nready<=0)continue;//no more useable sockfd 45 } 46 for(i=0;i<maxi;i++) 47 { 48 if((sockfd=client[i])<0) 49 { 50 continue; 51 } 52 if(FD_ISSET(sockfd,&rset)) 53 { 54 if((n=read(sockfd,buf,maxlen))==0) 55 { 56 close(sockfd); 57 FD_CLR(sockfd,&allset); 58 client[i]=-1; 59 }else 60 dowhatyouwant(); 61 if(--nready<=0) 62 { 63 break; 64 } 65 } 66 67 68 } 69 70 71 } 72 73 74 75 return 0; 76 }