如何使用NSURLConnection使连接保持活动状态?

时间:2015-05-11 11:26:50

标签: ios nsurlconnection

我正在使用NSURLConnection连接到服务器,并且能够向服务器发送请求,并且我在委托方法中得到响应。

-(void) sendRequest() {
    NSString *jsonPostBody = [NSString stringWithFormat:@"{\"width\":640,\"height\":480,\"ip\":\"SOME-IP\"}"];

    NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://SOME_IP:PORT/PATH"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%lu", (unsigned long)[postData length]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];

    theConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];

    if (theConnection) {
        self.receivedData = [[NSMutableData alloc]init];
        [theConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [theConnection start];
    } else {

        // Inform the user that the connection failed.

        UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [connectFailMessage show];

    }

    NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
    [dd setObject:@"ravi" forKey:@"name"];
}
}

在委托方法中,我能够接收数据。

问题 - 经过一段时间,比如一分钟服务器显示连接通道已关闭,我没有关闭任何地方的连接,我使用wireshark监控我的网络,显示http FIN 设置

enter image description here

enter image description here

如何使用nsurlconnection让我的连接活着?

由于

0 个答案:

没有答案