【问题标题】:using NSInputStream/NSOutputStream to communicate over TCP (iPhone)使用 NSInputStream/NSOutputStream 通过 TCP (iPhone) 进行通信
【发布时间】:2012-07-26 17:13:28
【问题描述】:

是否可以在 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”错误消息

【问题讨论】:

    标签: iphone networking tcp nsstream nsinputstream


    【解决方案1】:

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

    Using NSStreams For A TCP Connection Without NSHost

    【讨论】:

    • 谢谢,我在原始帖子中提到了这一点,尽管这是一个有效的答案。我仍在尝试弄清楚 inputStreamWithURL: 是否可以使用,如果可以,如何使用。
    • 我很确定你不能。想一想... 对outputStreamWithURL: 的调用如何意味着知道您希望这是与之前对inputStreamWithURL: 的调用相同的TCP/IP 连接,而不是一个新连接?
    • 我不确定,但由于使用了相同的 NSURL 对象,这似乎是可能的。如果你是对的,那么这些 API 的目的是什么?它们似乎没用。
    • 据我所知,它们旨在与文件 URL 一起使用。例如,inputStreamWithURL: 的 Apple 文档是这样说的:“创建并返回一个初始化的 NSInputStream 对象,该对象从给定 URL 的文件中读取数据。”话虽如此,我有点同意你的看法,我不确定使用 URL 引用文件的好处是什么(除非它是提供跨平台路径)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多