2013-04-30 117 views
0

我需要查找Web服務器(有時在http中,有時在https中)是否正在偵聽。我希望同步進行,並有一個很短的超時時間,例如2-3秒。iOS,檢查http或https服務器是否正在偵聽特定端口

什麼是正確的方法來做到這一點?我需要與iOS 5向後兼容。

更新:我需要在沒有外部庫的情況下執行此操作。

回答

3

由於OP無法使用外部庫,實現NSURLConnectionDelegate及用途:

- (void)testUrl:(NSString *)url 
{ 
    // Create the request. 
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url] 
               cachePolicy:NSURLRequestReloadIgnoringCacheData 
              timeoutInterval:3.0]; 

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; 
    int responseStatusCode = [httpResponse statusCode]; 

    NSLog(@"GOT STATUS CODE: %d", responseStatusCode); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"Done!"); 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 
+0

謝謝,我應該提到,我不能更新,以適應回答這個時候 – cateof 2013-04-30 17:56:34

+0

添加外部代碼。 – 2013-04-30 18:01:30

+0

這工作?我不認爲' - [NSURLConnection initWithRequest:]'會在這裏返回零。您需要檢查委託方法是否有錯誤。有關更多詳細信息,請參閱http://stackoverflow.com/questions/3978020/when-does-nsurlconnections-initwithrequest-return-nil。 – Mar0ux 2013-05-01 07:10:17

相關問題