Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLConnection ignores Keep-Alive timeout?

I'm converting my app to use HTTPS and would like to avoid the handshake cost as much as possible by keeping open a long-lived connection.

From reading the web and other answers on stack overflow it appears NSURLConnection should transparently keep the underlying socket open if the server responds with Connection: keep-alive and Keep-Alive: timeout=N.

However I am seeing that my connections are only kept open for around 10 seconds. My Keep-Alive response is set to much more than this. I am also sending Connection: keep-alive in my request headers.

Can anyone shed some light on this? I really don't want to have to use CFNetwork to achieve this.

like image 292
ileitch Avatar asked Feb 22 '12 13:02

ileitch


People also ask

What happens when HTTP keep alive timeout?

The keep alive timeout on the Message Processor allows a single TCP connection to send and receive multiple HTTP requests/responses from/to the backend server, instead of opening a new connection for every request/response pair.

How do you extend keep alive timeout?

Type KeepAliveTimeout, and then press ENTER. On the Edit menu, click Modify. Type the appropriate time-out value (in milliseconds), and then click OK. For example, to set the time-out value to two minutes, type 120000.

How to set connection Keep Alive?

To enable Keep-Alive, you need to explicitly request it via the HTTP header by accessing . htaccess or the main configuration file of your web server. If you turn on Keep-Alive, the HTTP response header will show Connection: keep-alive.


1 Answers

You have two ways:

As Tyler states in his answer here:

You can specify a timeout in your NSURLRequest object. One way to do this is to construct it via the requestWithURL:cachePolicy:timeoutInterval: method. (You can pass in the default NSURLRequestUseProtocolCachePolicy cachePolicy parameter if you don't want to worry about that part.) The timeout is a floating-point value in seconds, as are basically all time intervals in the iPhone SDK.

Also make sure your NSURLConnection's delegate is set and responds to the connection:didFailWithError: method. A connection always calls either this method or connectionDidFinishLoading: upon connection completion.

Or do what Kris suggests in his answer here:

ASIHTTPRequest has an expirePersistentConnections method. It may do what you're looking for.

It's not a drop-in replacement for NSURLConnection, but it's not too hard to port code from NSURLConnection to ASIHTTPRequest.

like image 91
Mina Nabil Avatar answered Oct 20 '22 23:10

Mina Nabil