Reputation: 816
Im trying to send and receive 2 data back to back on tcp socket. Protocol is written below.
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);
}
Upvotes: 0
Views: 5255
Reputation: 6566
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;
}
Upvotes: 3