gpt4 book ai didi

iphone - 如何在 iOS 中将 CFReadStreamRead 设置为超时?

转载 作者:行者123 更新时间:2023-11-28 18:40:11 27 4
gpt4 key购买 nike

我有在 iOS 上使用 CFReadStreamRead 的遗留代码,但如果没有/丢失连接,CFReadStreamRead 将永远阻塞。如何设置 CFReadStreamRead 超时?

提前致谢

最佳答案

@Michael Wildermuth 是的,打开流时出错并已修复。遇到同样问题的人,下面的代码会有所帮助。

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
CFStreamClientContext dataStreamContext = {0, (__bridge void *)(self), NULL, NULL, NULL};

CFHTTPMessageRef message = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (__bridge CFURLRef)url, kCFHTTPVersion1_1);

NSString *header;
NSDictionary *requestHeaders = [NSDictionary dictionaryWithObject:@"application/html;charset=UTF-8" forKey:@"Content-Type"];
for (header in requestHeaders) {
CFHTTPMessageSetHeaderFieldValue(message, (__bridge CFStringRef)header, (__bridge CFStringRef)[requestHeaders objectForKey:header]);
}

CFHTTPMessageSetBody(message, (CFDataRef)(CFSTR("")));

CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, message);
CFOptionFlags events = kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;


if(CFReadStreamSetClient(readStream, events, EvenCallBack, &dataStreamContext)){
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}

CFReadStreamOpen(readStream);

对于回调函数,

void EvenCallBack(CFReadStreamRef readStream, CFStreamEventType type, void *clientCallBackInfo){


if(CFReadStreamHasBytesAvailable(readStream))
{
uint8_t buf[1024];
unsigned int len = 1024;

CFIndex numBytesRead = CFReadStreamRead(readStream, buf, len);

NSMutableData* data = [[NSMutableData alloc] init];
[data appendBytes:&buf length:numBytesRead];

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"Network read (%d): %@", len, str);
}else {
return;
}

CFHTTPMessageRef message = (CFHTTPMessageRef)CFReadStreamCopyProperty((CFReadStreamRef)readStream, kCFStreamPropertyHTTPResponseHeader);
if (!message) {
NSLog(@"No message");
}

}

谢谢!

关于iphone - 如何在 iOS 中将 CFReadStreamRead 设置为超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910600/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com