c ++ socket recv函数循环

时间:2015-03-24 10:57:09

标签: c++ sockets

我试图在tcp套接字上重新发送和接收2个数据。议定书如下。

  1. 客户端发送数据
  2. 在服务器上接收数据后,它会发送回客户端
  3. 现在使用下面的客户端代码,我无法获得第二个数据,而且我认为' Recv'功能做错了。以下是代码段。

    int Recv(char* buffer, int size) 
    {
      int total = 0, n = 0;
      while((n = ::recv(m_hSocket, buffer+total, size-total-1, 0)) > 0) 
      {
        total += n;
      }
      buffer[total] = 0;
      return total;
    }
    
    int SendAndReceiveData()
    {
      //CStringA cstData :: this data getting filled by some other code. Ignore!
    
      //Send data
      char chSendBuff[256];
      memset(chSendBuff, 0, sizeof(chSendBuff));
      sprintf_s(chSendBuff, sizeof(chSendBuff), "%s", (LPCTSTR)cstData);
      send(m_hSocket, chSendBuff, (int)strlen(chSendBuff), 0);
    
      //Read response
      char chRecvBuff[256];
      memset(chRecvBuff, 0, sizeof(chRecvBuff));
      int iRet = Recv(chRecvBuff, 256);
    }
    

1 个答案:

答案 0 :(得分:2)

您的接收功能应如下所示:

int receive(int sockfd, void *buf, size_t len, int flags)
{
    size_t toread = len;
    char  *bufptr = (char*) buf;

    while (toread > 0)
    {
        ssize_t rsz = recv(sockfd, bufptr, toread, flags);
        if (rsz <= 0)
            return rsz;  /* Error or other end closed connection */

        toread -= rsz;  /* Read less next time */
        bufptr += rsz;  /* Next buffer position to read into */
    }

    return len;
}