Reputation: 2035
sprintf(send_data,"GET / HTTP/1.1\r\nHost: %s\r\n\r\n",hoststr);
printf("%s",send_data);
send(sock,send_data,strlen(send_data), 0);
while(bytes_recieved)
{
bytes_recieved=recv(sock,recv_data,1024,0);
printf("%d\n",bytes_recieved);
if(bytes_recieved==0){ break; }
recv_data[bytes_recieved] = '\0';
printf("%s" , recv_data);
}
When I request for example "www.example.com", I get the whole page and then at the end after two or three seconds I get bytes_received printed ('0') and then the loop breaks.
Why it takes 2-3 seconds to break the loop?
Is there a better way to implement simple http client then this?
Thanks.
Upvotes: 2
Views: 5150
Reputation: 201517
As an optimization for the HTTP protocol, version 1.1 adds default persistent connections (aka Connection: Keep-Alive
). The keep-alive holds the connection open so that you can send additional requests over the "reliable" channel; you can find additional information about that portion of the HTTP protocol in RFC2616 Section 8.1 - Persistent Connections.
Upvotes: 1
Reputation: 409442
When recv
returns 0
it means that the other end of the connection has nicely closed the connection.
HTTP is, from the beginning, a pure request-response protocol, where each request got a response followed by a closed connection.
What you're seeing here is that first you receive the requested page, then after a timeout (due to the newer versions of the HTTP protocol (that you say you support) keeps the connection open) a closed connection from the server.
Upvotes: 1