无法从服务器接收jpeg图像

时间:2013-01-25 05:33:30

标签: iphone ios objective-c sockets

我正在尝试从我的c#服务器接收jpeg图像。奇怪的是,当我使用调试器运行它并且在方法中的任何地方都有一个断点时它工作得很好。没有断点,我得到这个错误

损坏的JPEG数据:数据段的过早结束

这是我的代码

(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSMutableData *data;
data = [NSMutableData new];
switch(eventCode) {
    case NSStreamEventHasBytesAvailable:
    {
        uint8_t buffer[1024];
        int len;

        while([inputStream hasBytesAvailable]) {
            len = [inputStream read:buffer maxLength:sizeof(buffer)];

            if (len > 0)
            {
                [data appendBytes:(const void*)buffer length:sizeof(buffer)];
            }
        }
        UIImage *images = [[UIImage alloc]initWithData:data];
        [dvdCover setImage:images];
    } break;
    case NSStreamEventEndEncountered:
    {
        //UIImage *images = [[UIImage alloc]initWithData:data];
        //[dvdCover setImage:images];


    } break;
}

}

2 个答案:

答案 0 :(得分:0)

您似乎假设整个JPEG图像将在一个块中传输,您可以在一次出现'HasBytesAvailable'事件时读取它。但是,您还应该考虑将JPEG图像以多个块传输给您的情况。

如果设置断点,它可能对您有用,因为您的代码执行可能会在某处停止,并且您的网络缓冲区有足够的时间来接收图像的所有字节。但没有断点,可能没有时间这样做。

尝试重构代码以累积字节块,并且只假设在传输完所有字节后完成。 (通常你必须事先知道图像的字节数 - 或者你可以捕获流事件的结尾)

答案 1 :(得分:0)

hi you can check this code hop it will help you...

case NSStreamEventHasBytesAvailable:
{

uint32_t max_size = 1000000;  // Max size of the received imaged you can modify it as your reqirement.
        NSMutableData* buffer = [[NSMutableData alloc] initWithLength: max_size];
        NSInteger totalBytesRead = 0;
        NSInteger bytesRead = [(NSInputStream *)stream read: [buffer mutableBytes] maxLength: max_size];
        if (bytesRead != 0) {
            while (bytesRead > 0 && totalBytesRead + bytesRead < max_size) {
                totalBytesRead+= bytesRead;
                bytesRead = [(NSInputStream *)stream read: [buffer mutableBytes] + totalBytesRead maxLength: max_size - totalBytesRead];
            }
            if (bytesRead >= 0) {
                totalBytesRead += bytesRead;
            }
            else {
                // read failure, report error and bail (not forgetting to release buffer)
            }
            [buffer setLength: totalBytesRead];
            yourImageName.image = [UIImage imageWithData: buffer];
            [buffer release];

}  break;