我正在使用 ftp 协议下载文件。现在,为了检查处理错误的能力,我正在模拟一些网络错误的发生。处理网络 inputStream 的代码如下:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
#pragma unused(aStream)
assert(aStream == self.networkStream);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
self.connected = YES;
} break;
case NSStreamEventHasBytesAvailable: {
NSInteger bytesRead;
uint8_t buffer[32768];
// Pull some data off the network.
bytesRead = [self.networkStream read:buffer maxLength:sizeof(buffer)];
DLog(@"%@,byteRead:%d",self.urlInput,bytesRead);
if (bytesRead == -1) {
[self _stopReceiveWithStatus:@"Network read error"];
} else if (bytesRead == 0) {
[self _stopReceiveWithStatus:@"success"];
} else {
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream write:&buffer[bytesWrittenSoFar] maxLength:bytesRead - bytesWrittenSoFar];
DLog(@"%@,bytesWritten:%d",self.urlInput,bytesWritten);
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self _stopReceiveWithStatus:@"File write error"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != bytesRead);
}
} break;
case NSStreamEventHasSpaceAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventErrorOccurred: {
[self _stopReceiveWithStatus:@"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
assert(NO);
} break;
default: {
assert(NO);
} break;
}
}
如果我手动关闭wifi或关闭我的无线路由器(网络连接标志关闭),将返回“NSStreamEventErrorOccurred”并正确终止下载过程。但是,如果我关闭调制解调器,同时保持无线路由器打开(网络连接标志打开)。下载过程卡在“NSStreamEventHasBytesAvailable”的情况下。即使我打开互联网连接,它仍然卡住。
我想知道它为什么卡住以及如何检测到这种错误。我该如何处理这种情况?