recv stalls or does not return all data (C code)

421 Views Asked by At

I have a web service written in .net on a remote computer with IIS, I am trying to connect to it with a C program using socker to do a SOAP request.

My problem is that I have some probem receiving the data:

The receiving data loop does not work in a way or in another.

If I write:

nByte = 1;
while(nByte!=512)
{
   nByte = recv(sockfd,buffer,512, 0);
   if( nByte < 0 )
   {
      // check the error
   }
   if( nByte > 0)
   {
      // append buffer to received data
   }
}

sometime does not return all data, if it run without debugger and breackpoints.

If I try: while(nByte!=0) at the end of data it stalls and go in error.

How is it supposed to be done? Thanks, Antonino

** EDIT ** I resolved my situation in another way, I check the returned value for soap xml end:

nByte = 1;
while(nByte!=0)
{
   nByte = recv(sockfd,buffer,512, 0);
   if( nByte < 0 )
   {
      // check the error
   }
   if( nByte > 0)
   {
      // append nByte buffer to received data
      if( strstr("</soap:Envelope>", buffer) != NULL)
        break;
   }
}

It is very sad...

2

There are 2 best solutions below

0
On

Where does it say it fills the buffer? Read the man image. It blocks until at least one byte of data can be transferred, then transfers whatever data has arrived.

6
On
#define BUFFERSIZE 512  

byte buffer[BUFFERSIZE];
int nByte = BUFFERSIZE;
int rByte;  

while(nByte!=0)
{
   rByte = recv(sockfd, &buffer[BUFFERSIZE-nByte], nByte, 0);
   if( rByte < 0 )
   {
      // socket error
      break;
   }
   if( rByte == 0)
   {
      // connection closed by remote side or network breakdown, buffer is incomplete
      break;
   }
   if(rByte>nByte)
   {
     // impossible but you must check it: memory crash, system error
     break;
   }
   nByte -= rByte;  // rByte>0 all is ok
   // if nByte==0 automatically end of loop, you read all
   // if nByte >0 goto next recv, you need read more bytes, recv is prtialy in this case
} 

//**EDIT**   

if(nByte!=0) return false;

// TO DO - buffer complete