是否为每个NSStreamEventHasBytesAvailable调用read:maxLength:一次正确? [英] Is calling read:maxLength: once for every NSStreamEventHasBytesAvailable correct?

查看:141
本文介绍了是否为每个NSStreamEventHasBytesAvailable调用read:maxLength:一次正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

流编程指南:

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {

    switch(eventCode) {
        case NSStreamEventHasBytesAvailable:
        {
            if(!_data) {
                _data = [[NSMutableData data] retain];
            }
            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream *)stream read:buf maxLength:1024];
            if(len) {
                [_data appendBytes:(const void *)buf length:len];
                // bytesRead is an instance variable of type NSNumber.
                [bytesRead setIntValue:[bytesRead intValue]+len];
            } else {
                NSLog(@"no buffer!");
            }
            break;
        }
        // continued

如果可用字节数大于缓冲区大小怎么办?

What if the number of bytes available is larger than the buffer size?

在这种情况下,一次调用- read:maxLength:仅消耗可用字节的一部分,而是整个事件.如果它是最后一个NSStreamEventHasBytesAvailable,则剩余的字节会丢失.

In such a case, calling - read:maxLength: once only consumes part of available bytes but the whole event. If it is the last NSStreamEventHasBytesAvailable then the remaining bytes are lost.

所以在我看来,这段代码是不正确的.正确的代码应该使用循环来消耗每个NSStreamEventHasBytesAvailable的所有可用字节.

So it seems to me this code is not correct. The correct code should use a loop to consume all available bytes for every NSStreamEventHasBytesAvailable.

我是对的吗?示例代码有误吗?

Am I right? Is the sample code wrong?

推荐答案

调用一次read:maxLength:即可.如果您没有读取所有可用数据,则将收到另一个HasBytesAvailable事件.

Calling read:maxLength: once will work. If you do not read all of the available data then you will receive another HasBytesAvailable event.

循环读取所有数据可能是一个问题.如果数据继续到达,那么您可能会饿死该运行循环上安排的其他任务.如果您只读取一次,则将允许其他运行循环任务在下一个HasBytesAvailable事件传递之前运行.

Looping to read all of the data can be a problem. If data continues to arrive then you may starve other tasks scheduled on that run loop. If you instead only read once then other run loop tasks will be allowed to run before the next HasBytesAvailable event is delivered.

这篇关于是否为每个NSStreamEventHasBytesAvailable调用read:maxLength:一次正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆