使用NSURLConnection进行长轮询 [英] Long polling with NSURLConnection

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

问题描述

我正在开发一个iPhone应用程序,它将使用长轮询通过HTTP从服务器向客户端发送事件通知。在服务器上打开连接后,我发送了一小部分代表事件的JSON。我发现 - [NSURLConnectionDelegate connection:didReceiveData] 直到关闭连接后才被调用,无论我在创建的NSURLRequest 。我已经验证了服务器端正在按预期工作 - 第一个JSON事件将立即发送,后续事件将在发生时通过线路发送。有没有办法使用 NSURLConnection 来接收这些事件,或者我需要转而使用CFSocket API?

I'm working on an iPhone application which will use long-polling to send event notifications from the server to the client over HTTP. After opening a connection on the server I'm sending small bits of JSON that represent events, as they occur. I am finding that -[NSURLConnectionDelegate connection:didReceiveData] is not being called until after I close the connection, regardless of the cache settings I use when creating the NSURLRequest. I've verified that the server end is working as expected - the first JSON event will be sent immediately, and subsequent events will be sent over the wire as they occur. Is there a way to use NSURLConnection to receive these events as they occur, or will I need to instead drop down to the CFSocket API?

我开始集成CocoaAsyncSocket,但是如果可能的话,我更愿意继续使用 NSURLConnection ,因为它与我的其他REST /它更适合基于JSON的Web服务结构。

I'm starting to work on integrating CocoaAsyncSocket, but would prefer to continue using NSURLConnection if possible as it fits much better with the rest of my REST/JSON-based web service structure.

推荐答案

NSURLConnection 将缓冲数据正在下载并使用 didReceiveData 方法将其全部返回给您。 NSURLConnection 类无法区分网络延迟和数据中的故意拆分。

NSURLConnection will buffer the data while it is downloading and give it all back to you in one chunk with the didReceiveData method. The NSURLConnection class can't tell the difference between network lag and an intentional split in the data.

你会要么像你提到的那样需要使用像CFSocket这样的低级网络API(你可以访问每个字节,因为它来自网络接口,并且可以区分你负载的两个部分),或者你可以看看像 CURL 这样的库,看看那里有哪些类型的输出缓冲/非缓冲。

You would either need to use a lower-level network API like CFSocket as you mention (you would have access to each byte as it comes in from the network interface, and could distinguish the two parts of your payload), or you could take a look at a library like CURL and see what types of output buffering/non-buffering there is there.

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

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