【问题标题】:iPhone: Catching a Connection Error With NSStreamiPhone:使用 NSStream 捕获连接错误
【发布时间】:2010-09-10 18:15:44
【问题描述】:

我编写了一个程序,它使用 Apple 的流编程指南中概述的 NSStream 协议连接到给定 IP 上的服务器。数据的连接和传输完美无缺,但是如果用户指定了错误的 IP 并且程序尝试打开流,则会导致程序无响应。

根据我的阅读,handleEvent 方法检测到流错误,但是当我检查 eventCode == NSStreamEventErrorOccurred 的条件时,似乎什么也没发生。我的连接代码如下:

NSString *hostString = ipField.text;

    CFReadStreamRef readStream;

    CFWriteStreamRef writeStream;

    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)hostString, 10001, &readStream, &writeStream);



    inputStream = (NSInputStream *)readStream;

    outputStream = (NSOutputStream *)writeStream;

    [inputStream setDelegate:self];

    [outputStream setDelegate:self];

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [inputStream open];

    [outputStream open];

知道如何在无法建立连接时指定超时值或允许按钮触发关闭流吗?

【问题讨论】:

    标签: iphone cocoa connection stream nsstream


    【解决方案1】:

    关于如何指定 超时值或允许按钮 触发关闭流,如果 无法建立连接?

    使用NSTimer

    在您的 .h 中:

    ...
    @interface MyViewController : UIViewController
    {
        ...
        NSTimer* connectionTimeoutTimer;
        ...
    }
    ...
    

    在你的 .m 中:

    ...
    @interface MyViewController ()
    @property (nonatomic, retain) NSTimer* connectionTimeoutTimer;
    @end
    
    @implementation MyViewController
    
    ...
    @synthesize connectionTimeoutTimer;
    ...
    
    - (void)dealloc
    {
        [self stopConnectionTimeoutTimer];
        ...
    }
    
    // Call this when you initiate the connection
    - (void)startConnectionTimeoutTimer
    {
        [self stopConnectionTimeoutTimer]; // Or make sure any existing timer is stopped before this method is called
    
        NSTimeInterval interval = 3.0; // Measured in seconds, is a double
    
        self.connectionTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                                       target:self
                                                                     selector:@selector(handleConnectionTimeout:)
                                                                     userInfo:nil
                                                                      repeats:NO];
    }
    
    - (void)handleConnectionTimeout
    {
        // ... disconnect ...
    }
    
    // Call this when you successfully connect
    - (void)stopConnectionTimeoutTimer
    {
        if (connectionTimeoutTimer)
        {
            [connectionTimeoutTimer invalidate];
            [connectionTimeoutTimer release];
            connectionTimeoutTimer = nil;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多