本文主要是介绍CFNetwork编程1,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
学习ASIHTTPRequest的使用,是对apple提供的sdk 中CFNetwork的封装,实现了很多的功能。简单总结CFNetwork编程的基本内容。
包括 CFSocket类,CFStream类,CFHTTP类,CFFTP类。
CFStream:
CFReadStreamOpen(CFReadStreamRef ref);打开一个CFRedStream,就可以对其进行读,写等操作,这些操作会block,会suspend。可以通过在run loop中注册该stream可读、可写事件以及相应的callback函数,实现异步的读写。
CFStream内置支持SSL协议。
例:
CFWriteStreamRef myWriteStream =CFWriteStreamCreateWithFile(kCFAllocatorDefault, fileURL);
CFWriteStreamOpen(myWriteStream);
CFIndex numBytesRead;
UInt8 buf[myReadBufferSize];
numBytesRead = CFReadStreamRead(myReadStream, buf, sizeof(buf));
CFReadStreamClose(myReadStream);
CFRelease(myReadStream);
myReadStream = NULL;
实现异步的收发:
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host, port, &myReadStream, NULL);//创建连接,myReadStream和指定Host
//创建该流的context
CFStreamClientContext myContext = {0, myPtr, myRetain, myRelease, myCopyDesc};
// 注册读写该流相关的事件
CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (CFReadStreamSetClient(myReadStream, registeredEvents, myCallBack, &myContext))
{CFReadStreamScheduleWithRunLoop(myReadStream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
}
// 发起连接,open。。。。
if (!CFReadStreamOpen(myReadStream)) {CFStreamError myErr = CFReadStreamGetError(myReadStream);if (myErr.error != 0) { // An error has occurred.if (myErr.domain == kCFStreamErrorDomainPOSIX) {// Interpret myErr.error as a UNIX errno.strerror(myErr.error);} else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {OSStatus macError = (OSStatus)myErr.error;}// Check other domains.} else// start the run loopCFRunLoopRun();
}
callback的定义
void myCallBack (CFReadStreamRef stream, CFStreamEventType event, void *myPtr) {switch(event) {case kCFStreamEventHasBytesAvailable:.....UInt8 buf[BUFSIZE];CFIndex bytesRead = CFReadStreamRead(stream, buf, BUFSIZE);.....break;case kCFStreamEventErrorOccurred:CFStreamError error = CFReadStreamGetError(stream);reportError(error);CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);CFReadStreamClose(stream);CFRelease(stream);break;case kCFStreamEventEndEncountered:reportCompletion();CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);CFReadStreamClose(stream);CFRelease(stream);break;}
}
还有的方法是POLL,轮询
// 详细可参照
http://developer.apple.com/LIBRARY/IOS/#documentation/Networking/Conceptual/CFNetwork/CFStreamTasks/CFStreamTasks.html#//apple_ref/doc/uid/TP30001132-CH6-DontLinkElementID_12
这篇关于CFNetwork编程1的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!