iPhone:使用NSStream捕获连接错误

7
我已经编写了一个程序,使用苹果流编程指南中概述的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个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接