本文介绍了Objective-C 中的长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它使用 API 来获取网站上的实时更新.他们使用他们所谓的长轮询技术:

I have an application that uses an API to get real time updates on the website. They use what they call a long-polling technique:

长轮询是传统的投票技术和允许模拟信息从服务器推送到客户端.和长轮询,客户端请求来自服务器的信息类似于普通民意调查的方式.然而,如果服务器没有任何可供客户使用的信息,而不是发送空响应,服务器持有请求并等待以获得一些信息.一旦信息可用(或在合适的超时后),完整的响应被发送到客户.然后客户通常会立即重新请求信息从服务器,使服务器几乎总是有一个可用的等待它可以用来的请求响应事件传递数据.在 web/AJAX 上下文中,长轮询是也称为彗星编程.

长轮询本身不是推送技术,但可以在没有真正推动的情况可能.

Long polling is itself not a push technology, but can be used under circumstances where a real push is not possible.

基本上,这会强制在您收到响应后向服务器发出请求.在 iphone 应用程序中执行此操作的最佳方法是什么?这最终必须在后台运行.

Basically this enforces to make a request back to the server once you've got a response back. What is the best way to do this in an iphone application? This eventually has to run in the background.

推荐答案

这正是 NSURLConnection sendSynchronousRequest 最适合的用例:

This is exactly the sort of use-case that NSURLConnection sendSynchronousRequest is perfect for:

- (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 和委托回调来完成同样的事情,但在这种情况下这真的有点愚蠢.

Alternately, you could use async I/O and delegate callbacks to accomplish the same thing, but that would really be kind of silly in this case.

这篇关于Objective-C 中的长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 23:01