“Connection: Keep-Alive” in server response

2019-03-11 04:29发布

问题:

I'm trying to establish a HTTP persistent connection from a Silverlight application to a PHP page (ie without creating a new TCP connection for each HTTP request) hosted by an Apache server.

To this end, I need the webserver to send its HTTP responses with the "Connection" header set to "Keep-alive". Client-side, there doesn't seem to be any issue as the network API provided by Silverlight is basically a wrapper of the browser network capabilies, from what I've read : so if the browser supports HTTP 1.1 and Connection: Keep-Alive by default for its requests, it's fine. Content-Length is also well defined, so that the server knows when it has to send the response. However, the server response to the PHP request sets systematically "Connection:" to "close", thus ending the connection and preventing a persistent connection.

I've tried some things to work around this problem : different Methods (GET and POST), explicitly giving a "Connection: keep-alive" to the response with the following PHP code at the beginning of my script :

header("Connection: Keep-alive");

The latter adds the expected header to the response, which is good, but an additionnal "Connection: close" is still appended later in the response headers.

Is it a feature of PHP or Apache which enforces "close" (for some security or performance purpose, I'm guessing) or am I just missing something here ?

Thanks in advance.

P.S. : By sniffing packets, I've noticed that not many websites use "Keep-alive" and the TCP connection is reestablished. Isn't Keepalive the default and preferred behavior under HTTP 1.1 ?

回答1:

The Keep-Alive functionality is not meant for persistent connections.

Keep-Alive is meant to reduce the number of connections for a website. Instead of creating a new connection for each image/css/javascript in a webpage many requests will be made re-using the same connection.

There are some settings that prevent this in Apache too, like maximum number of requests on a connection or timeouts between requests. This will also eat your resources very fast because every connection needs its own thread.

You should switch to another solution, that is made for that kind of work.

For services that keep your connection open you can take a look at http://orbited.org and http://twistedmatrix.com/trac/



回答2:

Since PHP doesn't manage the HTTP connection, it has no way to change this setting. You need to set that in servers. For example, you can enable keep-alive like this in Apache if you are using mod_php,

KeepAlive On