Pregunta

I have the following code for testing purposes

for( int i = 0; i < 5 ; i++ ) {   
   var url = "http://myserver.com/Warmup";
   var request = WebRequest.Create(url);
   using (WebResponse response = request.GetResponse()) {
       using (var stream = response.GetResponseStream()) {
           using (var reader = new StreamReader(stream)) {
               reader.ReadToEnd();
           }
       }
   }
}

When I run it with Fiddler I see that only the first request has Connection: Keep-Alive header.

This means that if the server is IIS programmed to shutdown the application pool after some time of inactivity and that pool shutdown happens after the first request but before the next one then the next request that comes from the client will not have Connection: Keep-Alive set and so keep-alive will not kick in.

Why is Connection: Keep-Alive only sent for the first request and not for the later requests?

¿Fue útil?

Solución

HTTP/1.1 uses keep-alive connections by default. A client or server must explicitly indicate that they don't want Keep-Alive behavior by sending a Connection: close header.

The Connection: Keep-Alive header is sent on the first request only because the client doesn't yet know whether the server supports HTTP/1.1 or if it will return a HTTP/1.0 response. After the server confirms that it supports HTTP/1.1 by sending a response using that version, the client knows that it can safely drop the redundant header.

Otros consejos

I think it is because you are using a TCP connection for the request. Just as mentioned here the server creates one TCP connection which is in charge of all the requests you are performing.

Since TCP uses a three way handshake the server and client always know if the connection is still available or not. So everytime the server closes a connection it will send a so called FIN bit to the client so that the client knows that the connection is not established anymore.

Although you create the webrequest 5 times, the client already knows the request because it is available in its TCP/IP pool and can reuse the connection, unless the client demands to end the connection finally.

You can find more information in this wikipedia article about this topic.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top