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?
Use an
NSTimer
.In your .h:
In your .m: