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?