iPhone:使用NSStream捕获连接错误

时间:2010-09-10 18:15:44

标签: iphone cocoa connection stream nsstream

我编写了一个程序,使用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];

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

1 个答案:

答案 0 :(得分:9)

  

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

使用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;
    }
}