开发者

problem with NSInputStream on real iPhone

I have a problem with NSInputStream. Here is my code:

case NSStreamEventHasBytesAvailable:

        printf("BYTE AVAILABLE\n");

        int len = 0;
        NSMutableData *data = [[NSMutableData alloc] init];

        uint8_t buffer[32768];

        if(stream == iStream)
        {       
            printf("Receiving...\n");                       

            len = [iStream read:buffer maxLength:32768];                

            [data appendBytes:buffer length:len];                   

        } 
        [iStream close];

I try to read small data and it works perfectly on simulator and real iPhone. If I try to read large data (more than 4kB or maybe 5kB), the real iPhone just can read 2736 by开发者_如何转开发tes and stop.

Why is it? Help me plz! Merci d'avance!


Your data object needs to be external to your stream handler. It is often the case that when large abounts of data are coming in, you get it in chunks and not all at once. Just keep appending data to it until you receive bytesRead == 0; Then you can close your stream and use the data.

   case NSStreamEventHasBytesAvailable: {
        NSInteger       bytesRead;
        uint8_t         buffer[32768];

        // Pull some data off the network.

        bytesRead = [self._networkStream read:buffer maxLength:sizeof(buffer)];

        if (bytesRead == -1) {
            [self _stopReceiveWithFailure];
        } else if (bytesRead == 0) {
            [self _stopReceiveWithSuccess];
        } else {
            [data appendBytes:buffer length:len];                   
        }


Looks like you're creating a new data object every time... perhaps you should be creating & retaining it as a property, and appending to it as you are above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜