if(bind(listenfd,(struct sockaddr *)&server_addr,sizeof server_addr) < 0)
{
printf("socket bind error: %s\n",strerror(errno));
return 0;
}
listen(listenfd,10);
FD_ZERO(&rset);
FD_ZERO(&wrset);
FD_ZERO(&allset);
FD_SET(listenfd,&allset);
maxfd = listenfd;
maxid = -1;
while(1)
{
rset = allset;
nready = select(maxfd + 1, &rset,&wrset,NULL,NULL);
if(nready < 0)
{
printf("select error: %s\n",strerror(errno));
exit(1);
}
if(FD_ISSET(listenfd, &rset))
{
connfd = Accept(listenfd,&cli_addr);
printf("recieve from : %s at port %d\n", inet_ntop(AF_INET,&cli_addr.sin_addr,addr_str,INET_ADDRSTRLEN),cli_addr.sin_port);
for(ix = 0; ix < static_cast<int>(client.size()); ix++)
{
if(client[ix] < 0)
{
client[ix] = connfd;
break;
}
}
printf("client[%d] = %d\n",ix,connfd);
if( FD_SETSIZE == ix)
{
printf("too many client! \n");
exit(1);
}
if( connfd > maxfd)
{
maxfd = connfd;
}
FD_SET(connfd, &allset);
accepted++;
printf("accepted: %d\n",accepted);
if(ix > maxid)
{
maxid = ix;
}
if(--nready == 0)
{
continue;
}
}
for(ix = 0; ix <= maxid; ix++)
{
if((sockfd = client[ix]) < 0)
{
continue;
}
if(FD_ISSET(sockfd,&rset))
{
int left_len = bufMap[sockfd].length();
if( 0 == (nrcv = Read(sockfd,bufMap)))
{
client[ix] = -1;
printf("close! \n");
FD_CLR(sockfd,&allset);
bufMap.erase(sockfd);
close(sockfd);
}
else if ( nrcv > 0)
{
printf("nrcv = %d \n",nrcv);
nrcv += left_len;//next time when client write to