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.
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.
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.
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.
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 therequestWithURL:cachePolicy:timeoutInterval:
method. (You can pass in the defaultNSURLRequestUseProtocolCachePolicy
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 theconnection:didFailWithError:
method. A connection always calls either this method orconnectionDidFinishLoading:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With