Is calling read:maxLength: once for every NSStreamEventHasBytesAvailable correct?

[亡魂溺海] 提交于 2019-12-20 04:51:11

问题


Sample code from Stream Programming Guide:

- (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?

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.

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/29224004/is-calling-readmaxlength-once-for-every-nsstreameventhasbytesavailable-correct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!