我的iOS应用程序包含2个版本:服务器和客户端。服务器通过 Bonjour 发布服务并等待客户端。客户端搜索该服务并连接到服务器。之后,所有通信都通过CFSockets实施。
以下是我为此类通信设置流的代码:
- (BOOL)setupSocketStreams {
if ( readStream == nil || writeStream == nil ) {
return NO;
}
incomingDataBuffer = [[NSMutableData alloc] init];
outgoingDataBuffer = [[NSMutableData alloc] init];
// Turning SSL on
NSDictionary *sslSettings = [NSDictionary dictionaryWithObjectsAndKeys:(id)kCFBooleanFalse, (id)kCFStreamSSLValidatesCertificateChain, nil];
CFReadStreamSetProperty(readStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
CFReadStreamSetProperty(readStream, kCFStreamPropertySSLSettings, sslSettings);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertySocketSecurityLevel, kCFStreamSocketSecurityLevelNegotiatedSSL);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertySSLSettings, sslSettings);
CFReadStreamSetProperty(
readStream,
kCFStreamPropertyShouldCloseNativeSocket,
kCFBooleanTrue
);
CFWriteStreamSetProperty(
writeStream,
kCFStreamPropertyShouldCloseNativeSocket,
kCFBooleanTrue
);
CFOptionFlags registeredEvents =
kCFStreamEventOpenCompleted |
kCFStreamEventHasBytesAvailable |
kCFStreamEventCanAcceptBytes |
kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred
;
CFStreamClientContext ctx = {
0, // version
self, // info
NULL, // retain callback
NULL, // release callback
NULL // copyDescription callback
};
CFReadStreamSetClient(
readStream,
registeredEvents,
readStreamEventHandler,
&ctx
);
CFWriteStreamSetClient(
writeStream,
registeredEvents,
writeStreamEventHandler,
&ctx
);
CFReadStreamScheduleWithRunLoop(
readStream,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes
);
CFWriteStreamScheduleWithRunLoop(
writeStream,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes
);
if ( ! CFReadStreamOpen(readStream) || ! CFWriteStreamOpen(writeStream)) {
[self close];
return NO;
}
if ([self.delegate respondsToSelector:@selector(establishedConnection:)]) {
[self.delegate establishedConnection:self];
}
return YES;
}
如果没有部分,在此代码上打开SSL可以正常工作,但否则我会收到错误:
Error:
The operation couldn’t be completed. (OSStatus error -9800.)
会是什么样的问题?
谢谢!
iOS 5 中的 TLS1.2 支持存在一个已知问题:https://developer.apple.com/library/ios/#technotes/tn2287/_index.html#//apple_ref/doc/uid/DTS40011309
通过将kCFStreamSSLLevel设置为@"kCFStreamSocketSecurityLevelTLSv1_0SSLv3",我能够修复应用程序中的-9800问题。