Click to See Complete Forum and Search --> : Sockets- a problem in recieving enough data


sam_kannan
August 2nd, 2005, 01:18 AM
In one of our applications we have written a small piece of code to receive 2047 bytes of data through a socket. If the bytes received is less than 2047 then a while loop is executed where additional data is received till a total of 2047 bytes are received. I have given the code below(without log statements). The problems is that in one of our customer sites it received only about 530 bytes of data at a particular point of time. Can some one tell me what is the problem with the code?


CODE:


long lRet;
long lTotalBytesReceived = 0;
DWORD dwErr;



lRet = recv(*sckt,lpszPacket,2047,0);
if (lRet < 0)
{
dwErr = WSAGetLastError();

}
catch(...)
{

}

lTotalBytesReceived = lRet;
long lRet2;
if( lTotalBytesReceived < 2047 && lTotalBytesReceived > 0 )
{
long lBytesRemaining;
char lpszTemp[2048];

while (lTotalBytesReceived != 2047)
{
memset(lpszTemp,0,2048);
lBytesRemaining = 2047 - lTotalBytesReceived;

lRet2 = recv(*sckt,lpszTemp,lBytesRemaining,0);
if ((lRet2 <= 0) || (lRet2 > lBytesRemaining))
{
dwErr = WSAGetLastError();
break;
}

sprintf(lpszPacket,"%s%s",lpszPacket,lpszTemp);
lTotalBytesReceived = lTotalBytesReceived + lRet2;

}
}

mistersulu
August 5th, 2005, 09:32 AM
You never know how big a packet will be. Try something more like this:


int recvd;
int total = 0;
char *buf;

buf = (char *) malloc(2047);
while (total < 2047)
{
switch ((recvd = recv(sock, *(char *)(buf + total), 2047 - total, 0)):
{
case -1:
// error (if non-blocking check for wouldblock)
return;
case 0:
// closed on other side
return;
default:
total += recvd;
}
}


Just FYI, next time surround your code like this [ code ] ...some code [ /code ]

Hope this helps.

sulu