I am trying to learn socket programming but I am having trouble with partial recv-ing.
I want to get all the text in yahoo.com/index.html.
Code:
TCPClient client("www.yahoo.com",80);
client.setTimeOut(1,0);
client.write("GET http://www.yahoo.com/index.html HTTP/1.1\nHost: www.yahoo.com\n\n");
cout << client.read();
I only get 512 bytes at a time using my recv function so that is why I loop it.
During the first few loops the select function returns 1 and the recv function returns 512. After all the text has been downloaded from yahoo the select function keeps returning 1 and the recv function returns 0. Therefore it gets stuck in an infinite while loop.
I thought the select function returned 0 when the recv function didn't have any data to return and would also return 0. Should I just set the while loop to stop when size equals 0 or I am using these functions wrong? I meant for the while loop to stop when there was no more data to receive from the the socket, which is what I though select told me. How should I do this correctly?
Code:
std::string TCPClient::read()
{
std::string buffer;
char b[512];
int size = 0;
FD_ZERO(&mReadFds);
FD_SET(mSocket, &mReadFds);
int error = select(mSocket + 1, &mReadFds, 0, 0, &mTimeOut);
while (error > 0)
{
if(FD_ISSET(mSocket, &mReadFds))
{
size = recv(mSocket, b, 512, 0);
if (size == SOCKET_ERROR)
{
mState = CS_BROKEN;
return buffer;
}
b[size] = 0;
buffer += b;
}
FD_ZERO(&mReadFds);
FD_SET(mSocket, &mReadFds);
error = select(mSocket + 1, &mReadFds, 0, 0, &mTimeOut);
std::cout << "error: " << error << std::endl;
std::cout << "size: " << size << std::endl;
}
if (error == SOCKET_ERROR)
{
mState = CS_BROKEN;
return buffer;
}
mState = CS_CONNECTED;
return buffer;
}
Thanks for any help.