检测服务器是否可访问

时间:2011-03-24 03:17:41

标签: iphone objective-c ios4 ipad

我有一个连接到Web服务器的iPad应用程序。我需要检查Web服务器当时是否正在运行。如果Web服务器关闭,我必须向用户提示消息。我该怎么做?

感谢。

4 个答案:

答案 0 :(得分:3)

我已经非常成功地使用了ASIHttpRequest library附带的Reachability类来验证特定服务器是否可以通过网络访问。此博客文章介绍了如何执行此操作:http://blog.ddg.com/?p=24

答案 1 :(得分:2)

您应该使用超时值(requestWithURL:cachePolicy:timeoutInterval:)构造NSURLRequest以完全不处理任何响应。如果达到超时值,您将获得委托回调didFailWithError:

如果你没有得到,最终NSURLConnection会给你一个didReceiveResponse:。在那里你需要解释NSURLResponse代码,你可以在那里处理通常的HTTP响应代码(200,404,500等)。

确定您是否有任何互联网连接是一个不同的问题 - 您应该考虑使用Apple的Reachability代码样本。

答案 2 :(得分:1)

我就这样做了:

  1. 获取Readability.h/m from the Apple Sample Projects并将其放入项目
  2. 安装下面的NetworkObserver.h / m
  3. 当应用程序在[“AppDelegate”didFinishLaunchingWithOptions]中启动时,使用[ [NetworkObserver currentObserver] start]启动NetworkObserver
  4. 当应用程序进入后台(applicationDidEnterBackground)时停止它,当它进入前台(applicationWillEnterForeground)然后再次启动它
  5. 当您需要测试它时,请使用以下代码:
  6. 如何使用它的代码:

    NetworkObserver *observer = [NetworkObserver currentNetworkObserver];
    if( observer.internetActive && observer.hostActive ) {
        // Do whatever you need to do with the Network
    } else {
        if( !observer.internetActive ) {
            if( anError ) {
                *anError = [NSError errorWithDomain:NetworkErrorDomain code:1212 userInfo:[NSDictionary dictionaryWithObject:@"Internet is not active at the moment" forKey:NSLocalizedDescriptionKey]];
            }
        } else {
            if( anError ) {
                *anError = [NSError errorWithDomain:NetworkErrorDomain code:1221 userInfo:[NSDictionary dictionaryWithObject:@"Host is cannot be reached" forKey:NSLocalizedDescriptionKey]];
            }
        }
    }
    

    首先是NetworkObserver.h的代码

    #import <Foundation/Foundation.h>
    
    @class Reachability;
    
    @interface NetworkObserver : NSObject {
    @private
        BOOL internetActive;
        BOOL hostActive;
    
        Reachability* internetReachable;
        Reachability* hostReachable;
    }
    
    @property (nonatomic) BOOL internetActive;
    @property (nonatomic) BOOL hostActive;
    
    @property (nonatomic, retain) Reachability* internetReachable;
    @property (nonatomic, retain) Reachability* hostReachable;
    
    // Checks the current Network Status
    - (void) checkNetworkStatus:(NSNotification *)notice;
    
    - (void) start;
    - (void) stop;
    
    + (NetworkObserver *) currentNetworkObserver;
    
    @end
    

    最后是NetworkObserver.m的代码:

    #import "NetworkObserver.h"
    
    #import "Reachability.h"
    #import "Constants.h"
    
    static NetworkObserver *networkObserver;
    
    @implementation NetworkObserver
    
    @synthesize internetReachable, hostReachable;
    @synthesize internetActive, hostActive;
    
    +(void) initialize {
        if( !networkObserver ) {
            networkObserver = [[NetworkObserver alloc] init];
        }
    }
    
    + (NetworkObserver *) currentNetworkObserver {
        return networkObserver;
    }
    
    - (id) init {
        self = [super init];
        if( self ) {
            self.internetReachable = [[Reachability reachabilityForInternetConnection] retain];
            // check if a pathway to a random host exists
            DLog( @"NO.init(), host name: %@", kServerHostName );
            self.hostReachable = [[Reachability reachabilityWithHostName:kServerHostName] retain];
        }
        return self;
    }
    
    - (void) start {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
        [internetReachable startNotifier];
        [hostReachable startNotifier];
        [self checkNetworkStatus:nil];
    }
    
    - (void) stop {
        [internetReachable stopNotifier];
        [hostReachable stopNotifier];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    - (void) checkNetworkStatus:(NSNotification *)notice
    {
        // called after network status changes
    
        NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
        switch (internetStatus)
        {
            case NotReachable:
            {
                DLog(@"The internet is down.");
                self.internetActive = NO;
                break;
            }
            case ReachableViaWiFi:
            {
                DLog(@"The internet is working via WIFI.");
                self.internetActive = YES;
                break;
            }
            case ReachableViaWWAN:
            {
                DLog(@"The internet is working via WWAN.");
                self.internetActive = YES;
                break;
            }
        }
    
        if( notice ) {
            NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
            switch (hostStatus)
            {
                case NotReachable:
                {
                    DLog(@"A gateway to the host server is down.");
                    self.hostActive = NO;
                    break;
                }
                case ReachableViaWiFi:
                {
                    DLog(@"A gateway to the host server is working via WIFI.");
                    self.hostActive = YES;
                    break;
                }
                case ReachableViaWWAN:
                {
                    DLog(@"A gateway to the host server is working via WWAN.");
                    self.hostActive = YES;
                    break;
                }
            }
        } else {
            DLog(@"No notice received yet so assume it works");
            self.hostActive = YES;
        }
    }
    
    @end
    

    顺便说一句,只需将DLog替换为NSLog,使其工作(我在发布App时使用预处理器指令将NSLog取出)。

    另一方面,有很多other post on Stack OverFlow that deal with that issue like this one

    另请注意,NetworkObserver需要一些时间才能获得正确的值,因此您可能无法在启动时使用它。

答案 3 :(得分:0)

我认为最简单的解决方案是创建一个可以ping的测试文件。也许像serverping.txt这样的东西只有'ok'作为它的内容(以保持数据负载最小)。如果您的响应statusCode是503(或者可能是500 ......您必须测试),那么您就知道该服务不可用。