#include#include#include#include#include#include#include#include#include#defineMYPORT 1234//the port users will be connecting to#defineBACKLOG 5//how many pending connections queue will hold#defineBUF_SIZE 200intfd_A[BACKLOG];//accepted connection fdintconn_amount;//current connection amountvoidshowclient()
{inti;
printf("client amount: %d\n", conn_amount);for(i=0; i
printf("[%d]:%d", i, fd_A[i]);
}
printf("\n\n");
}intmain(void)
{intsock_fd, new_fd;//listen on sock_fd, new connection on new_fdstructsockaddr_in server_addr;//server address informationstructsockaddr_in client_addr;//connector's address informationsocklen_t sin_size;intyes=1;charbuf[BUF_SIZE];intret;inti;if((sock_fd=socket(AF_INET, SOCK_STREAM,0))==-1) {
perror("socket");
exit(1);
}if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR,&yes,sizeof(int))==-1) {
perror("setsockopt");
exit(1);
}
server_addr.sin_family=AF_INET;//host byte orderserver_addr.sin_port=htons(MYPORT);//short, network byte orderserver_addr.sin_addr.s_addr=INADDR_ANY;//automatically fill with my IPmemset(server_addr.sin_zero,'\0',sizeof(server_addr.sin_zero));if(bind(sock_fd, (structsockaddr*)&server_addr,sizeof(server_addr))==-1) {
perror("bind");
exit(1);
}if(listen(sock_fd, BACKLOG)==-1) {
perror("listen");
exit(1);
}
printf("listen port %d\n", MYPORT);
fd_set fdsr;intmaxsock;structtimeval tv;
conn_amount=0;
sin_size=sizeof(client_addr);
maxsock=sock_fd;while(1) {//initialize file descriptor setFD_ZERO(&fdsr);
FD_SET(sock_fd,&fdsr);//timeout settingtv.tv_sec=30;
tv.tv_usec=0;//add active connection to fd setfor(i=0; i
FD_SET(fd_A[i],&fdsr);
}
}
ret=select(maxsock+1,&fdsr, NULL, NULL,&tv);if(ret<0) {
perror("select");break;
}elseif(ret==0) {
printf("timeout\n");continue;
}//check every fd in the setfor(i=0; i
ret=recv(fd_A[i], buf,sizeof(buf),0);if(ret<=0) {//client closeprintf("client[%d] close\n", i);
close(fd_A[i]);
FD_CLR(fd_A[i],&fdsr);
fd_A[i]=0;
}else{//receive dataif(ret
memset(&buf[ret],'\0',1);
printf("client[%d] send:%s\n", i, buf);
}
}
}//check whether a new connection comesif(FD_ISSET(sock_fd,&fdsr)) {
new_fd=accept(sock_fd, (structsockaddr*)&client_addr,&sin_size);if(new_fd<=0) {
perror("accept");continue;
}//add to fd queueif(conn_amount
fd_A[conn_amount++]=new_fd;
printf("new connection client[%d] %s:%d\n", conn_amount,
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));if(new_fd>maxsock)
maxsock=new_fd;
}else{
printf("max connections arrive, exit\n");
send(new_fd,"bye",4,0);
close(new_fd);break;
}
}
showclient();
}//close other connectionsfor(i=0; i
close(fd_A[i]);
}
}
exit(0);
}