我用select监测读时间,但是read出现了阻塞
maxfd = iListenFdIP;
maxi = -1;
for(i=0 ; i<CONNCT_NUM_MAX; ++i)
{
client[i][0] = -1;
}//for
FD_ZERO(&allset);
FD_SET(iListenFdIP , &allset);
i = 0;
while(1){
rset = allset;
nready = select(maxfd+1 , &rset , NULL , NULL , NULL);
// DEBUG(LOG_DEBUG,"nread:%d\n",nready);
if(FD_ISSET(iListenFdIP , &rset))
{
/*接收客户端的请求*/
clilen = sizeof(cliaddr);
// DEBUG(LOG_DEBUG,"\naccpet connection~\n");
if((connfd = accept( iListenFdIP, (struct sockaddr *)&cliaddr , &clilen)) < 0)
{
DEBUG(LOG_ERROR,"accept error.\n");
continue;
}//if
DEBUG(LOG_DEBUG,"accpet a new client: %s:%d\n", inet_ntoa(cliaddr.sin_addr) , cliaddr.sin_port);
/*将客户链接套接字描述符添加到数组*/
for(i=0 ; i<CONNCT_NUM_MAX ; ++i)
{
if(client[i][0] < 0)
{
client[i][0] = connfd;
client[i][1] = cliaddr.sin_port;
break;
}//if
}//for
if(CONNCT_NUM_MAX == i)
{
DEBUG(LOG_ERROR,"too many connection.\n");
}//if
else
{
FD_SET(connfd , &allset);
if(connfd > maxfd)
maxfd = connfd;
if(i > maxi)
maxi = i;
}
if(--nready < 0)
continue;
}//if
// DEBUG(LOG_DEBUG,"maxi:%d\n",maxi);
for(i=0; i<=maxi ; ++i)
{
memset(caBuff,0x0,sizeof(caBuff));
memset(sndBuff,0x0,sizeof(sndBuff));
memset(caSplitBuff,0x0,sizeof(caSplitBuff));
if((sockfd = client[i][0]) < 0)
continue;
if(FD_ISSET(sockfd , &rset))
{
/*处理客户请求*/
//DEBUG(LOG_DEBUG,"\nreading the socket~~~ \n");
if((n = read(sockfd , caBuff , sizeof(caBuff))) <= 0)
{
DEBUG(LOG_DEBUG,"client[%d] is close\n",i);
close(sockfd);
FD_CLR(sockfd , &allset);
client[i][0] = -1;
}//if
else{
char* cpPosNow = caBuff;
if ( NULL == (cpPos = strchr(cpPosNow, '\n'))){
DEBUG(LOG_ERROR,"data:%s can't find '\n' \n",cpPosNow);
continue;
}
iPkgLen = cpPos - cpPosNow;
memcpy(caSplitBuff, cpPosNow, iPkgLen);
inet_aton(caSplitBuff,&addr.sin_addr);
memset(caSplitBuff,0x0,sizeof(caSplitBuff));
memcpy(&tmpIP,&addr.sin_addr,4);
//tmpIP = htonl(tmpIP);
memcpy(caSplitBuff,&tmpIP,4);
if(NULL == (pIpMapHashNode = ipmap_hash_table_lookup((const unsigned char *)caSplitBuff))){
res = send(sockfd, "IPOFFLINE\n",strlen("IPOFFLINE\n") , 0);
if(res < 0){
close(sockfd);
FD_CLR(sockfd , &allset);
client[i][0] = -1;
DEBUG(LOG_DEBUG,"Send ERROR:Client is close,ErrorNum = %d, ErrorMsg = %s\n", errno, strerror(errno));
}
}
else{
DEBUG(LOG_DEBUG,"recv IPV4:%d.%d.%d.%d username:%s dstprot:%d\n",
caSplitBuff[0],caSplitBuff[1],caSplitBuff[2],caSplitBuff[3],pIpMapHashNode->UserName,client[i][1]);
memcpy(sndBuff, pIpMapHashNode->UserName, strlen(pIpMapHashNode->UserName));
strcat(sndBuff,"\n");
res = send(sockfd, sndBuff, strlen(pIpMapHashNode->UserName)+1, 0);
if(res <= 0){
close(sockfd);
FD_CLR(sockfd , &allset);
client[i][0] = -1;
DEBUG(LOG_DEBUG,"ERROR:Send Client is close,ErrorNum = %d, ErrorMsg = %s\n", errno, strerror(errno));
}
}
}
if(--nready <= 0)
break;
}
}
}
close(iListenFdIP);
return;