2
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.

4
  • 2
    At a guess? Keep-alive. Try using "HTTP/1.0" Commented Feb 21, 2014 at 19:30
  • HTTP/1.0 works without waiting 2-3 seconds why is that? Commented Feb 21, 2014 at 19:32
  • 3
    By default, HTTP 1.1 uses "Connection: Keep-Alive". This is because most web pages have more than one file that needs to be downloaded from the server; you don't have to reconnect to get the CSS for example. I believe you can get this behavior in HTTP 1.1 by specifying "Connection: Close" in the headers. Commented Feb 21, 2014 at 19:33
  • Also, if you're going to use 1.1 you should probably add an "Accept" header. See also HTTP pipelining and persistent connection. Commented Feb 21, 2014 at 19:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.