我正在尝试使用 CFStream 进行简单的 HTTP 通信,但是使用下面的代码,即使我提供了无效的 URL (wwwww.yahoo.com),我仍然可以成功连接。
有人可以指出我这段代码有什么问题吗?我预计对 CFReadStreamOpen() 的调用会失败,但即使 URL 错误,它也会成功。
我还没有找到一个简单的 CFNetwork 示例,它可以在 ARC 上运行 HTTP(不使用 NSURL)。如果有人知道这样的示例代码,请告诉我。
- (void) test
{
CFStringRef m_host = CFStringCreateWithCString(NULL, "wwwww.yahoo.com", kCFStringEncodingASCII);
int m_port = 80;
CFHostRef host;
NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
{
CFReadStreamRef m_in = NULL;
CFWriteStreamRef m_out = NULL;
host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
if (!host)
{
NSLog(@"Error resolving host %@", m_host);
}
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
CFRelease(host);
CFStreamClientContext context = {0, nil,nil,nil,nil};
if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
{
CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
}
if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
{
CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGe tCurrent(),kCFRunLoopCommonModes);
}
BOOL success = CFReadStreamOpen(m_in);
CFErrorRef error = CFReadStreamCopyError(m_in);
if (!success || (error && CFErrorGetCode(error) != 0))
{
NSLog(@"Connect error %s : %ld", CFErrorGetDomain(error), CFErrorGetCode(error));
[NSThread sleepForTimeInterval:5.0];
}
success = CFWriteStreamOpen(m_out);
error = CFReadStreamCopyError(m_in);
if (!success || (error && CFErrorGetCode(error) != 0))
{
NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
[NSThread sleepForTimeInterval:5.0];
}
else
{
NSLog(@"Connected");
}
}
}