CFStream IOS Socket通信

时间:2011-12-24 02:13:18

标签: iphone objective-c ios sockets cfreadstream

如何清除CFStream缓冲区? 每次我从套接字读取时,仍然存在来自旧请求的数据,我的意思是完全响应旧请求而不仅仅是它的一个片段。

我错过了什么吗?

这是我用来初始化连接的函数:

-(void)openSocketConnection:(UInt32)port: (NSString *)host
{
  NSString *hoststring  = [[NSString alloc] initWithString:host];
  CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,(__bridge CFStringRef)hoststring ,
port,&_nnet_readStream,&_nnet_writeStream);

CFWriteStreamCanAcceptBytes(_nnet_writeStream);

CFWriteStreamSetProperty(_nnet_writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

CFReadStreamSetProperty(_nnet_readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

    if(!CFWriteStreamOpen(_nnet_writeStream)) {
        NSLog(@"Error Opening Write Socket");
    }
    if(!CFReadStreamOpen(_nnet_readStream)) {
        NSLog(@"Error Opening Write Socket");
    }

}

这是我用来从套接字读取数据的函数:

BOOL done = NO;
NSMutableString* result = [NSMutableString string];
while (!done) 
{
        if (CFReadStreamHasBytesAvailable(_nnet_readStream)) 
        {
            UInt8 buf[1024];
            CFIndex bytesRead = CFReadStreamRead(_nnet_readStream, buf, 1024);
            if (bytesRead < 0) 
            {
                CFStreamError error = CFReadStreamGetError(_nnet_readStream);
                NSLog(@"%@",error);
            } else if (bytesRead == 0) 
            {
                if (CFReadStreamGetStatus(_nnet_readStream) == kCFStreamStatusAtEnd) 
                {
                    done = YES;
                }
            } else 
            {
                [result appendString:[[NSString alloc] initWithBytes:buf length:bytesRead encoding:NSUTF8StringEncoding]];
            }
        } else 
        {
            done = YES;
        }
}   

1 个答案:

答案 0 :(得分:0)

您似乎认为,当您从另一端的主机获取数据时,它将始终一次性可用。

我不知道底层协议是什么,但一般情况下,远程端完全有可能尝试发送1600个字节,然后你将获得1500字节但是必须等待几毫秒(甚至几秒) )接下来的100个字节。同时CFReadStreamHasBytesAvailable将返回false,因此即使您没有读取服务器发送的所有数据,您的代码也会设置完成标志。