我正在使用 iOS 7 的 Multipeer Connectivity Framework 在两台设备之间发送文件。我正在使用 NSStreams 传输文件,因为我之前尝试使用 MCSession 的 sendData:toPeers:withMode 确实不可靠。不幸的是,我得到的传输速度非常慢,大约 100kb/s,这不适用于我正在处理的应用程序。这是我的输入和输出流委托方法,这是文件传输发生的地方。
输出流(在流的委托中)
...//previous code
case NSStreamEventHasSpaceAvailable: {
//we will only open the stream when we want to send the file.
NSLog(@"Stream has space available");
//[self updateStatus:@"Sending"];
// If we don't have any data buffered, go read the next chunk of data.
if (totalBytesWritten< outgoingDataBuffer.length) {
//more stuff to read
int towrite;
int diff = outgoingDataBuffer.length-packetSize;
if (diff <= totalBytesWritten)
{
towrite = outgoingDataBuffer.length - totalBytesWritten;
} else
towrite = packetSize;
NSRange byteRange = {totalBytesWritten, towrite};
uint8_t buffer[towrite];
[outgoingDataBuffer getBytes:buffer range:byteRange];
NSInteger bytesWritten = [outputStream write:buffer maxLength:towrite];
totalBytesWritten += bytesWritten;
NSLog(@"Written %d out of %d bytes",totalBytesWritten, outgoingDataBuffer.length);
} else {
//we've written all we can write about the topic?
NSLog(@"Written %d out of %d bytes",totalBytesWritten, outgoingDataBuffer.length);
[self endStream];
}
// If we're not out of data completely, send the next chunk.
} break;
输入流
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
NSLog(@"Bytes Available");
//Sent when the input stream has bytes to read, we need to read bytes or else this wont be called again
//when this happens... we want to read as many bytes as we can
uint8_t buffer[1024];
int bytesRead;
bytesRead = [inputStream read:buffer maxLength:sizeof(buffer)];
[incomingDataBuffer appendBytes:&buffer length:bytesRead];
totalBytesRead += bytesRead;
NSLog(@"Read %d bytes, total read bytes: %d",bytesRead, totalBytesRead);
}break;
case NSStreamEventEndEncountered:
{
UIImage *newImage = [[UIImage alloc]initWithData:incomingDataBuffer];
[[self.detailViewController imageView] setImage:newImage];
NSLog(@"End Encountered");
[self closeStream];
//this should get called when there aren't any more bytes being sent down the stream
}
}
}
有没有办法通过多线程或使用稍微修改的使用异步套接字的 NSStream 子类来加速此文件传输?