iOS,检查http或https服务器是否正在侦听特定端口

问题描述:

我需要查找Web服务器(有时在http中,有时在https中)是否正在侦听。我希望同步进行,并有一个很短的超时时间,例如2-3秒。iOS,检查http或https服务器是否正在侦听特定端口

什么是正确的方法来做到这一点?我需要与iOS 5向后兼容。

更新:我需要在没有外部库的情况下执行此操作。

由于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://*.com/questions/3978020/when-does-nsurlconnections-initwithrequest-return-nil。 – Mar0ux 2013-05-01 07:10:17