Question

Is it possible to do TCP communications using NSInputStream/NSOutputStream on iPhone? The example apple gives in their documentation uses [NSStream getStreamsToHost] and that isn't supported on iPhone. I have seen other posts which use CFStream to set up the socket and then bridge to NSStream, is that the only supported way?

Based on the documentation it seems something like this should work in theory:

//input stream
NSURL *url = [[NSURL alloc] initWithString:@"10.252.1.1:8080"];

iStream = [NSInputStream inputStreamWithURL:url];
[iStream setDelegate:self];

[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];

oStream = [NSOutputStream outputStreamWithURL:url append:true];
[oStream setDelegate:self];

[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];

However there are two problems with this:

1) If I do just the iStream part I never see any events called on my delegate.

2) The outputStreamWithURL fails with a cryptic "EXC_BAD_ACCESS" error message which comes from within CFWriteStreamSetProperty

Was it helpful?

Solution

This Apple article explains how to implement getStreamsStreamsToHost on iOS

Using NSStreams For A TCP Connection Without NSHost

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top