简体   繁体   English

CFStream IOS套接字通信

[英]CFStream IOS Socket communication

how can i clear an CFStream buffer? 如何清除CFStream缓冲区? Everytime i read from socket there is still data from an old request, i mean complete response to an old request not just a fragment of it. 每当我从套接字读取时,仍然有来自旧请求的数据,我的意思是对旧请求的完全响应,而不仅仅是它的一部分。

Am i missing something ? 我想念什么吗?

This is a function i use to initialize the connection: 这是我用来初始化连接的函数:

-(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");
    }

}

This is a function i use to read data from 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;
        }
}   

You seem to assume that when you get data from the host on the other end it will always be available all in one go. 您似乎以为,当您从另一端的主机获取数据时,它总是可以一次访问所有数据。

I don't know what the underlying protocol is, but in general it's entirely possible that the remote end will try and send 1600 bytes and that you'll get 1500 bytes but then have to wait a few milliseconds (or even seconds) for the next 100 bytes. 我不知道底层协议是什么,但是通常来说,远端很可能会尝试发送1600个字节,而您将获得1500个字节,但是必须等待几毫秒(甚至几秒钟)的时间,接下来的100个字节。 Meanwhile CFReadStreamHasBytesAvailable would return false and so your code would set your done flag even though you haven't read all the data the server sent. 同时, CFReadStreamHasBytesAvailable将返回false,因此即使您没有读取服务器发送的所有数据,您的代码也将设置完成标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM