1

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

Locksleyu
  • 5,192
  • 8
  • 52
  • 77

1 Answers1

1

This Apple article explains how to implement getStreamsStreamsToHost on iOS

Using NSStreams For A TCP Connection Without NSHost

idz
  • 12,825
  • 1
  • 29
  • 40
  • Thanks, I alluded to that in my original post though it is a valid answer. I am still trying to figure out if inputStreamWithURL: can be used, and if so, how. – Locksleyu Jul 27 '12 at 19:47
  • I'm fairly sure you can't. Think about it... How is the call to `outputStreamWithURL:` meant to know that you want this to be the same TCP/IP connection as the previous call to `inputStreamWithURL:` and not a new one? – idz Jul 27 '12 at 20:52
  • I'm not sure, but since the same NSURL object is used it seems possible. If you are right then what are the purpose of these APIs? They seem useless. – Locksleyu Jul 30 '12 at 17:52
  • As far as I know, they are intended for use with file URLs. For example, here's what the Apple docs for `inputStreamWithURL:` say: "Creates and returns an initialized NSInputStream object that reads data from the file at a given URL." That being said, I sort of agree with you, I am not sure what the advantage of using a URL to refer to a file is (unless it is to provide a cross-platform path). – idz Jul 30 '12 at 18:26