On Sep 10, 2010, at 12:52 PM, Carter R. Harrison wrote:
> I'm working on a app that establishes a network connection using NSStream. I
> found though that the code does not behave very well when it is trying to
> connect to an unreachable IP address or an IP address that just isn't
> accepting connections on the port I have specified. The code I'm using is
> below. Does anybody have any good ideas on how to detect a connection
> timeout or a complete connection failure? Apple's documentation indicates
> that if a connection cannot be established the NSInputStream and
> NSOutputStream returned will be nil, but for some reason my checks for that
> never seem to work. Any help is appreciated and thanks in advance.
>
> NSHost *host = [NSHost hostWithAddress:address];
> [NSStream getStreamsToHost:host port:port inputStream:&is outputStream:&os];
>
> if (!is || !os)
> {
> NSLog(@"This line doesn't execute, even with a bogus IP address");
> }
>
> buffer = [[NSMutableData alloc] initWithCapacity:0];
> [is retain];
> [os retain];
>
> [is open];
> [os open];
No attempt to connect to the host is made until the -open calls are made. This
is necessary to allow you to configure the nature of the connection that will
be made between when you obtain the stream object and when the connection is
initiated. It's also necessary so that you can set the delegate before
initiating the connection.
The documentation seems to be in error about returning nil pointers if the
connection fails. I assume it means that the stream objects can be nil if the
host or port are totally invalid, or if some low-level problem occurs (like the
socket() call fails due to running out of file descriptors).
The code you showed doesn't schedule the streams on a runloop, which it should.
If you want a timeout, schedule a timer. If the timer fires before the
NSStreamEventOpenCompleted arrives, then you've timed out. Respond as
appropriate (shut down the streams, etc.).
Regards,
Ken
___
Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to arch...@mail-archive.com