使用NSInputStream / NSOutputStream通过TCP(iPhone)进行通信

时间:2012-07-26 17:13:29

标签: iphone networking tcp nsstream nsinputstream

是否可以在iPhone上使用NSInputStream / NSOutputStream进行TCP通信?苹果在他们的文档中给出的示例使用了[NSStream getStreamsToHost]并且在iPhone上不支持。我看过其他帖子使用CFStream设置套接字然后桥接到NSStream,这是唯一支持的方式吗?

基于文档,似乎这样的事情应该在理论上起作用:

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

然而,这有两个问题:

1)如果我只做iStream部分,我从来没有看到任何在我的代表上调用的事件。

2)outputStreamWithURL失败,出现一条来自CFWriteStreamSetProperty

的隐藏式“EXC_BAD_ACCESS”错误消息

1 个答案:

答案 0 :(得分:1)

这篇Apple文章解释了如何在iOS上实现getStreamsStreamsToHost

Using NSStreams For A TCP Connection Without NSHost

相关问题