Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
int TCPClient::Read(char* data,int len ,int timeout , char * delem,int delm_len,int &r)
{
 int l;
     timeval t_out;

         fd_set set;
   
       t_out.tv_sec = timeout;

       t_out.tv_usec = 0;

       FD_ZERO(&set);   

       FD_SET(Socket,&set);
      
         l = select(Socket +1, &set, NULL, NULL, &t_out);
      
         setsockopt(Socket,SOL_SOCKET,SO_RCVTIMEO|SO_LINGER,(char*)&t_out,sizeof(struct timeval));

       if(l==0)
         {
          printf("\n time out %i \n",timeout);
          return -10;
         }
       
         else if(len<0)
          {
         printf("\n error in select 2 TCPClient \n");
       
           return -5;
          }
         
     char a[2] = "\0";
    
       memset(data,0,strlen(data));
      // strcpy(data," ");   
     ssize_t l1;
     int i = 0;
     int cycle = 0;
     while(true)
     {
     
          l1 = recv(Socket,a,1,0);
          if(l1==0)
          {
          printf("\n closed \n");
          i = 0;
            break;
          }
        
          if(l1 == -1)
          {
            cycle++;
            if(r==5 && cycle<4)
             {
                sleep(1);
                printf("wait");
                    continue;
             }
             
            break;
          }
            data =  stpcpy(data,a);
          i +=l1;
         
          if(delm_len>1 && strstr(data,delem)!=NULL)
          {
            printf("\n hit strstr \n  ");
            break;
          }
            else if(delm_len==1 && delem[0]==a[0])
            { 
            r = 1;
                break;
            }
            if(i>=len && r==1)
            break;
            
      }//while(i< len) ;    
      // printf("\n data recv %i  r = %i ",i,r);
       //printf("\n block data return %s \n",data);
 	return i; 
}
Posted

1 solution

The receive call blocks all the time, not just sometimes. A blocking call with a timeout is still a blocking call. In any case, recv() will always return something, you just have to check to make sure it's data and not just returning because of a timeout or a socket closure.
 
Share this answer
 
Comments
Mahmoud_Gamal 10-Jun-15 4:05am    
thanks for response
but some time connected server hang recv still block for ever
Albert Holguin 10-Jun-15 10:22am    
Perhaps you should set the linger option separately, since it requires a different structure. Your setsockopt() call may be failing, you're not checking the return.
Mahmoud_Gamal 11-Jun-15 4:31am    
thanks i will try for that
thanks alot :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900