我正在尝试使用套接字和流向另一台设备发送消息,使用此处的代码:
http://mobileorchard.com/tutorial-networking-and-bonjour-on-iphone/
这工作正常,我可以从一个设备发送一条消息,让另一台设备接收它并毫无问题地阅读它。对于较大的消息,包括诸如 NSData 之类的内容,它会在发送消息时冻结我的 UI,因此我想在后台线程上运行它。我的代码看起来一样,除了实现了后台线程:
dispatch_queue_t queue = dispatch_queue_create("com.App.SendMessage", NULL);
dispatch_async(queue, ^{
NSMutableDictionary *mutable = [[NSMutableDictionary alloc] init];
[mutable setObject:@"Test" forKey:@"TestKey"];
[self.server sendMessage:mutable toService:service];
});
dispatch_release(queue);
消息代码如下所示:
NSData* rawPacket = [NSKeyedArchiver archivedDataWithRootObject:packet];
// Write header: lengh of raw packet
int packetLength = [rawPacket length];
[outgoingDataBuffer appendBytes:&packetLength length:sizeof(int)];
// Write body: encoded NSDictionary
[outgoingDataBuffer appendData:rawPacket];
// Try to write to stream
[self writeOutgoingBufferToStream];
- (void)writeOutgoingBufferToStream {
// Is connection open?
if ( !readStreamOpen || !writeStreamOpen ) {
// No, wait until everything is operational before pushing data through
return;
}
// Do we have anything to write?
if ( [outgoingDataBuffer length] == 0 ) {
return;
}
// Can stream take any data in?
if ( !CFWriteStreamCanAcceptBytes(writeStream) ) {
return;
}
// Write as much as we can
CFIndex writtenBytes = CFWriteStreamWrite(writeStream, [outgoingDataBuffer bytes], [outgoingDataBuffer length]);
if ( writtenBytes == -1 ) {
// Error occurred. Close everything up.
[self close];
[delegate connectionTerminated:self];
return;
}
NSRange range = {0, writtenBytes};
[outgoingDataBuffer replaceBytesInRange:range withBytes:NULL length:0];
}
它因错误而崩溃:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSConcreteMutableData replaceBytesInRange:withBytes:length:]: range {0, 1855} exceeds data length 0'
有人知道为什么这可能会在后台线程上崩溃吗?