繁体   English   中英

c ++ socket recv函数循环

[英]c++ socket recv function loop

我试图在tcp套接字上发送和接收2个数据。 协议写在下面。

  1. 客户端发送数据
  2. 在接收到服务器上的数据后,它将发送回客户端

现在使用下面的客户端代码,我无法获取第二个数据,并且我认为'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);
}

您的接收函数应如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM