所以我的应用程序按以下方式工作:
还有一些注意事项:NSInputStream和NSOutput流都在NSDefaultRunLoopMode中各自设备的currentRunLoop上运行。
运行此过程时,有时转换回NSDictionary工作正常,没有错误(大约1/3次尝试),但其他时候转换返回此错误:
错误:无法将NSData转换为NSDict:错误域= NSCocoaErrorDomain代码= 3840“第1行的意外字符b”UserInfo = {NSDebugDescription =第1行的意外字符b,kCFPropertyListOldStyleParsingError =错误域= NSCocoaErrorDomain代码= 3840“转换字符串失败了。“ UserInfo = {NSDebugDescription =字符串转换失败。}}
以下是解析流中数据的程序部分:
...处理流事件的方法:
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable: {
uint8_t buf[1024];
unsigned int len = (unsigned)[(NSInputStream *)aStream read:buf maxLength:1024];
if(len) {
[self handleEventBuffer:buf WithLength:len];
}
...
...以及处理数据的方法:
-(void)handleEventBuffer:(uint8_t*)buf WithLength:(unsigned int)len {
...
NSString *bufStr = [NSString stringWithFormat:@"%s",(const char*)buf];
if ([bufStr containsString:@"bplist00"] && [self.cameraData length] > 0) {
// Detected new file, enter in all the old data and reset for new data
NSError *error;
NSDictionary *tempDict = [[NSDictionary alloc] init];
tempDict = [NSPropertyListSerialization propertyListWithData:self.cameraData
options:0
format:NULL
error:&error];
if (error != nil) {
// Expected good file but no good file, erase and restart
NSLog(@"Error: Failed to convert NSData to NSDict : %@", [error description]);
[self.cameraData setLength:0];
}
...
[self.cameraData setLength:0];
[self.cameraData appendBytes:buf length:len];
} else {
// Still recieving data
[self.cameraData appendBytes:buf length:len];
}
所以,我得到的问题是:
答案 0 :(得分:1)
您似乎依赖于对流的每次写入,导致相同大小的匹配读取,您知道这是NSStream
保证的吗?如果没有,则任何读取都可能包含两个(或更多)编码字典的一部分,您将看到您看到的解析错误。
替代方法:
对于要发送的每个编码字典:
写完:
阅读结束:
如果您使用的是可靠的通信流,则应该可以让您可靠地读取每个编码的字典。它避免你试图找出每个编码字典之间的边界,因为该信息是你的协议的一部分。
HTH