简体   繁体   中英

c++ socket recv function loop

Im trying to send and receive 2 data back to back on tcp socket. Protocol is written below.

  1. Client send data
  2. On receiving the data on sever it sends back to client

Now using below client code I'm not able to get 2nd data and I think the 'Recv' function doing something wrong. Below is the code snippet.

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

Your receive function should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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