iPhone:使用NSStream捕获连接错误

iso*_*rik 7 iphone connection cocoa 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];
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*rog 9

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

用一个NSTimer.

在你的.h:

...
@interface MyViewController : UIViewController
{
    ...
    NSTimer* connectionTimeoutTimer;
    ...
}
...
Run Code Online (Sandbox Code Playgroud)

在你的.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;
    }
}
Run Code Online (Sandbox Code Playgroud)