0
我一直在iOS中进行客户端 - 服务器通信,但我在这里遇到了一个问题,我有一些麻烦要理解。NSStream过早关闭
我写了两个基本功能:一个发送数据到服务器,另一个接收来自服务器的数据。每个人都有一个叫做超时参数,允许使当前线程休眠和唤醒每0.25秒,直到达到超时:
-(ReturnCode) send : (NSData*)data :(int)timeOut
{
if(![self isConnectionOpened]) return KO;
float timer = 0;
while(![_outputStream hasSpaceAvailable])
{
[NSThread sleepForTimeInterval:0.25];
timer+=0.25;
if(timer == timeOut) break;
}
int ret = 0;
if([_outputStream hasSpaceAvailable]){
int lg = [data length];
ret = [_outputStream write:[data bytes] maxLength:lg];
if(ret == -1) return KO;
else return OK;
}
return TIMEOUT;
}
- (ReturnCode) receive : (NSData**)data : (int)timeOut : (int)maxLength
{
uint8_t buffer[maxLength];
int len;
NSMutableData* dataReceived = [[NSMutableData alloc] init];
if(! [self isConnectionOpened]) return KO;
float timer = 0;
while(![_inputStream hasBytesAvailable])
{
[NSThread sleepForTimeInterval:0.25];
timer+=0.25;
if(timer == timeOut) break;
}
if(![_inputStream hasBytesAvailable]) return TIMEOUT;
while ([_inputStream hasBytesAvailable]) {
len = [_inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
[dataReceived appendBytes:buffer length:len];
*data = dataReceived;
return OK;
}
}
return KO;
}
随着iPhone 4 + iOS6的,一切都会好的。但在iOS7下,出于某些模糊原因,inputstream和outputstream过早关闭(NSStreamEventErrorOccurred引发)。事实是,如果我在从服务器接收数据并使代码运行之前放置一个断点,它可以正常工作,读/写流不会错误地关闭。
所以我认为这是一个同步的问题,但我不明白为什么...如果任何人有想法,请帮助...