我使用iOS 7的Multipeer连接框架在两个设备之间发送文件。我使用NSStreams来传输文件,因为我之前使用MCSession的sendData:toPeers:withMode进行的尝试实际上是不可靠的。不幸的是,我得到的传输速度非常慢,大约100kb/s,这对于我正在处理的应用程序来说不起作用。这里是我的输入和输出流委托方法,这是文件传输发生的地方。使用Multipeer连接框架缓慢文件传输
输出流(在委托用于流)
...//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子类此文件传输那使用异步套接字?
你还在浏览同行吗?这篇文章(http://mzsanford.com/blog/ios7-multipeer-wifi-slow/index.html)讨论了浏览/广告如何影响你的整体wifi性能。另外,你是否有从设备到模拟器的工作?我可以从Sim转到Device,但是当我尝试发送给Sim时,我的输入流会尝试读取一次数据,并找到零数据,然后断开连接。 – Brian
嘿Brian。我的设置由两个运行分开的应用程序执行文件传输的ipad mini组成。在浏览器和广告客户连接后,我仍然在浏览同行,因为当我停止浏览同行时,我失去了与设备的连接。在使用sendData:toPeers方法时,我遇到了频繁断开连接的类似问题。这就是为什么我切换到使用Stream方法。 –
这只是奇怪,因为从设备到设备的空中下载工作如此之快,但执行文件传输非常慢。苹果必须为其自身的实现做一些幕后魔法。 –