CFNetwork持续连接(保持活跃)

时间:2011-10-17 12:58:03

标签: ios http cfnetwork persistent-connection

我试图通过Apple CFNetwork框架使用持久HTTP连接来减少我们的服务器开销。但是关于它的文档很少。我能找到的唯一信息表明,只要设置了适当的标志,框架就会代表开发人员回收流:

        CFHTTPMessageRef request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, methodString, url, kCFHTTPVersion1_1);
        CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Keep-Alive"), CFSTR("120")); <--- This line

        //Set message body if we're posting
        if (msDetails.eType == HttpRequestDetails::POST)
        {
            CFDataRef bodyRef = CFDataCreate(kCFAllocatorDefault, (const UInt8*)msDetails.strBody.c_str(), msDetails.strBody.length());
            CFHTTPMessageSetBody(request, bodyRef);
            CFRelease(bodyRef); 
        }

        //Create the read stream...
        CFReadStreamRef ReadStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request);

        //...use persistent connections..
        CFReadStreamSetProperty(ReadStream, kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue); <--- This line

        //...enable SSL if the URL is https
        if(msDetails.strURL[4] == 's')
        {
            //Hey an https request
            CFMutableDictionaryRef pDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
            CFDictionarySetValue(pDict, kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);
            CFDictionarySetValue(pDict, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelSSLv3);
            CFReadStreamSetProperty(ReadStream, kCFStreamPropertySSLSettings, pDict);
            CFRelease(pDict);
        }

        CFReadStreamOpen(ReadStream);

上述代码导致“CFNetwork内部错误”。如果我删除CFReadStreamSetProperty(ReadStream,kCFStreamPropertyHTTPAttemptPersistentConnection,kCFBooleanTrue)调用,那么我不再收到错误。还值得一提的是,一旦我读完数据后关闭了readstream,但也许我需要自己管理流池?

有没有人可以参考我的任何文档,示例或教程?我很想继续使用CFNetwork的东西,因为我们有一个客户坚持认为我们必须尽量减少对Obj-C的使用。

2 个答案:

答案 0 :(得分:1)

我一直在努力做同样的事情。

关键是要确保所有流设置对于请求完全相同。特别是,您必须将所有请求的EXACT相同字典对象传递给kCFStreamPropertySSLSettings。它们具有相同的内容是不够的,你必须重复使用完全相同的字典。

答案 1 :(得分:-1)

添加CFNetwork.framework

#import <CFNetwork/CFHTTPStream.h>