【问题标题】:recv stalls or does not return all data (C code)recv 停止或不返回所有数据(C 代码)
【发布时间】:2016-02-10 17:47:45
【问题描述】:

我在带有 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
   }
}

如果它在没有调试器和断点的情况下运行,有时不会返回所有数据。

如果我尝试: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;
   }
}

很伤心……

【问题讨论】:

    标签: c sockets recv winsockets


    【解决方案1】:
    #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
    

    【讨论】:

    • 以这种方式它只接收 READSIZE 字节,我希望它下载所有流直到连接关闭,但它永远不会返回 0。
    • "以这种方式它只接收 READSIZE 字节" - 不,我们探测读取所有,但并不总是套接字返回所有,我们必须阅读更多
    • 在我的回答中,没有错误,您会自动读取所有内容,并在没有探针读取 0 字节的情况下退出循环。如果 rByte==0 并且您没有读取所有内容 (nByte>0) - 连接在通信时被远程端关闭,它的连接不完整。
    • 我将 READSIZE 重命名为 BUFFERSIZE
    • 你标记为不可能的状态确实是不可能的。因此没有必要检查它。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2014-08-28
      • 1970-01-01
      • 2014-02-16
      • 2016-12-30
      相关资源
      最近更新 更多