我有一个使用 API 来获取网站实时更新的应用程序。他们使用他们所谓的长轮询技术 http://en.wikipedia.org/wiki/Push_technology#Long_polling:
长轮询是一种变体
传统的投票技术和
允许模拟信息
从服务器推送到客户端。和
长轮询,客户端请求
来自服务器的信息
与普通民意调查类似。然而,
如果服务器没有任何
为客户提供的信息,
而不是发送空响应,
服务器保留请求并等待
以获得一些信息。
一旦信息可用
(或在适当的超时后),
完整的响应发送至
客户。客户通常会这样
立即重新索取信息
从服务器,以便服务器
几乎总会有一个可用的
等待请求,它可以用来
传送数据以响应事件。
在 Web/AJAX 上下文中,长轮询是
也称为彗星编程。
长轮询本身并不是推送
技术,但可以在以下情况下使用
没有真正推动的情况
可能的。
基本上,一旦收到响应,就会强制向服务器发出请求。在 iPhone 应用程序中执行此操作的最佳方法是什么?这最终必须在后台运行。
这正是这种用例NSURLConnection sendSynchronousRequest
非常适合:
- (void) longPoll {
//create an autorelease pool for the thread
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//compose the request
NSError* error = nil;
NSURLResponse* response = nil;
NSURL* requestUrl = [NSURL URLWithString:@"http://www.mysite.com/pollUrl"];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];
//send the request (will block until a response comes back)
NSData* responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
//pass the response on to the handler (can also check for errors here, if you want)
[self performSelectorOnMainThread:@selector(dataReceived:)
withObject:responseData waitUntilDone:YES];
//clear the pool
[pool drain];
//send the next poll request
[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}
- (void) startPoll {
//not covered in this example: stopping the poll or ensuring that only 1 poll is active at any given time
[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}
- (void) dataReceived: (NSData*) theData {
//process the response here
}
或者,您可以使用异步 I/O 和委托回调来完成同样的事情,但在这种情况下这确实有点愚蠢。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)