NSURLConnection运行多次 [英] NSURLConnection is run many times

查看:90
本文介绍了NSURLConnection运行多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每隔5秒与服务器异步连接。 URL是相同的,但每次更改POST主体。现在我每次都从头开始创建NSURL,NSURLRequest和NSURLConnection。

I connect asynchronously with server each 5 seconds. The URL is the same, but POST-body is changed each time. Now I create NSURL, NSURLRequest and NSURLConnection from the scratch each time.

我认为设置连接一次更有效,只需进一步使用。
我是新手,不确定是否可能。没有可变的NSURLConnection,但可能需要创建NSURLConnection,如:

I think it'd be more effective to set connection once and just use that one further. I am a newbie and not sure if that possible. There is no mutable NSURLConnection, but may it's need to create NSURLConnection like:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

并更改NSMutableURLRequest POST数据以向服务器发送另一个请求。
哪种方式是对的?

and change NSMutableURLRequest POST-data to send another request to server. Which way is right?

推荐答案

我假设您关注的是创建HTTP连接的开销。 NSURLConnection非常智能,可以使用HTTP / 1.1并重用现有连接来处理此问题。上次我检查时它没有使用流水线操作,但出于您的目的,连接重用应该足够了。我鼓励你在这上面放一个网络嗅探器并确保它正常工作。

I assume what you're concerned about is the overhead of creating the HTTP connection. NSURLConnection is smart enough to handle this for you using HTTP/1.1 and reusing existing connections. It does not use pipelining last time I checked, but for your purpose, connection reuse should be sufficient. I do encourage you to put a network sniffer on this and make sure that it's working as you want them to.

创建对象本身的成本在订单上是微不足道的每5秒一次,你不应该尝试优化它(当然你应该重用NSURL)。这是开放与服务器的连接,价格昂贵,特别是在iPhone上。

The cost of creating the objects themselves is trivial on the order of once per 5s and you shouldn't try to optimize that (though of course you should reuse the NSURL). It's the opening a connection to the server that's expensive, especially on iPhone.

如果你发现你确实需要流水线操作,那么很遗憾你不得不自己动手。我听说CFHTTPStream可以做到,但我没有看到很多证据。 CocoaAsyncSocket是低级访问套接字的最佳选择,无需编写低级代码。

If you find you really do need pipelining, you unfortunately will have to roll your own. I've heard that CFHTTPStream can do it, but I don't see a lot of evidence of that. CocoaAsyncSocket is your best bet for low-level access to the sockets without having to write low-level code.

由于单元网络上的延迟可能非常糟糕,因此可能您的连接完成时间超过5秒。确保在开始下一个连接之前完成一个连接,或者你将开始建立越来越多的开放连接。

Since latency on the cell network can be very bad, it's possible that your connection will take longer than 5s to complete. Do make sure that one connection is done before starting the next, or you'll start making more and more open connections.

这篇关于NSURLConnection运行多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆