iPhone: Catching a Connection Error With NSStream

2019-02-13 13:03发布

问题:

I have written a program that connects to a server on a given IP using the NSStream protocol outlined in Apple's stream programming guide. The connection and transfer of data works flawlessly, however if the user specifies the wrong IP and the program attempts to open the streams it results in the program becoming unresponsive.

From what I have read, the handleEvent method detects stream errors, however when I check for the condition that eventCode == NSStreamEventErrorOccurred, nothing seems to happen. My connect code is as follows:

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

Any idea as to how I can specify a timeout value or allow for a button to trigger the closing of the streams if a connection cannot be made?

回答1:

Any idea as to how I can specify a timeout value or allow for a button to trigger the closing of the streams if a connection cannot be made?

Use an NSTimer.

In your .h:

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

In your .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;
    }
}