-->

Is calling read:maxLength: once for every NSStream

2020-04-19 06:39发布

问题:

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.



标签: ios nsstream