recv停止或不返回所有数据(C代码)

时间:2016-02-10 17:47:45

标签: c sockets recv winsockets

我在带有IIS的远程计算机上用.net编写了一个Web服务,我试图用一个C程序连接它,使用socker来做一个SOAP请求。

我的问题是我有一些探测器接收数据:

接收数据循环不能以某种方式工作。

如果我写:

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
   }
}

如果没有调试器和breackpoints运行,有时会返回所有数据。

如果我在数据末尾尝试:while(nByte!=0),它会停止并出错。

应该如何完成? 谢谢, 安东尼

** 编辑 ** 我以另一种方式解决了我的情况,我检查了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;
   }
}

非常难过......

2 个答案:

答案 0 :(得分:3)

#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

答案 1 :(得分:1)

它说填充缓冲区在哪里?阅读 man 图片。它会阻塞,直到至少可以传输一个字节的数据,然后传输所有已到达的数据。