真实的iPhone设备上是否有类似于“getStreamsToHost”的东西?

3
我想使用苹果的示例代码将NSOutputStream写入服务器:

NSURL *website = [NSURL URLWithString:str_IP];
NSHost *host = [NSHost hostWithName:[website host]];
[NSStream getStreamsToHost:host port:1100 inputStream:nil outputStream:&oStream];
[oStream retain];
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];

这些代码在iPhone模拟器上运行良好,但是当我将其构建到实际设备时,出现了两个警告。问题在于:

1)类NSHost不属于iphone os库

2)无法找到getStreamsToHost

有没有替代方法或类可用于实际设备?

1个回答

12

由于CFWriteStream与NSOutputStream之间是toll-free bridged,因此您可以使用CFStreamCreatePairWithSocketToHost来获取您的流配对:

CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)host, port, &readStream, &writeStream);
if (readStream && writeStream) {
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

    inputStream = (NSInputStream *)readStream;
    [inputStream retain];
    [inputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];

    outputStream = (NSOutputStream *)writeStream;
    [outputStream retain];
    [outputStream setDelegate:self];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream open];
}

if (readStream)
    CFRelease(readStream);

if (writeStream)
    CFRelease(writeStream);

谢谢。还有一个问题:无法找到“kCFStreamPropertyShouldCloseNativeSocket”。我应该使用“kCFStreamPropertySocketNativeHandle”代替,还是不设置CFWriteStream的属性? - Chilly Zhong
1
它在那里,你可能需要 #include <CFNetwork/CFSocketStream.h>。 - Matt Stevens
这里是由苹果实现的类别 - DanSkeel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接