"图像无法显示错误"在C ++中通过套接字发送图像时

时间:2017-02-28 18:58:43

标签: c++ image sockets

我试图通过套接字将所有类型的文件发送到C ++中的浏览器。我能够在套接字上发送。txt.html文件,但是当我尝试发送jpeg时,我收到错误The image "localhost:8199/img.jpg" cannot be displayed because it contains errors。我不确定为什么我的程序适用于发送文本文件但无法处理图像。这就是我读取文件并将其写入客户端的方式:

 int fileLength = read(in, buf, BUFSIZE);
    buf[fileLength] = 0;
    char *fileContents = buf;

    while (fileLength > 0) {

        string msg =  "HTTP/1.0 200 OK\r\nContent-Type:" + fileExt + "\r\n\r\n\r\nHere is response data";
        int bytes_written;

        if(vrsn == "1.1" || vrsn == "1.0"){
            write(fd, msg.c_str(), strlen(msg.c_str()));    
            bytes_written = write(fd, fileContents, fileLength);
        } else {
            bytes_written = write(fd, fileContents, fileLength);
        }

        fileLength -= bytes_written;
        fileContents += bytes_written;  
    }

完整代码在此处:http://pastebin.com/vU9N0gRi

如果我在浏览器网络控制台中查看响应标头,我发现Content-Typeimage/jpeg,所以我不确定我做错了什么。

图像文件的处理方式与普通文本文件不同吗?如果是这样,为了处理将图像文件发送到浏览器,我到底需要做些什么呢?

2 个答案:

答案 0 :(得分:3)

  

string msg =" HTTP / 1.0 200 OK \ r \ nContent-Type:" + fileExt +" \ r \ n \ r \ n \ r \ n \ n这里是响应数据&#34 ;;

这是二进制数据的无效HTTP响应,如图像。在HTTP标头末尾终止\r\n\r\n之后,之后的所有内容都是邮件正文数据。因此,您将\r\nHere is response data作为图像的前几个字节发送,从而破坏它们。您需要完全删除它,即使是txthtml文件。

更糟糕的是,您在每次循环迭代上发送msg,因此您在文件数据的每个缓冲区前面都有HTTP响应字符串,从而彻底破坏您的图像数据。

此外,您的回复缺少Content-LengthConnection: close回复标题。

尝试更像这样的东西:

int sendRaw(int fd, const void *buf, int buflen)
{
    const char *pbuf = static_cast<const char*>(buf);
    int bytes_written;

    while (buflen > 0) {
        bytes_written = write(fd, pbuf, buflen);
        if (written == -1) return -1;
        pbuf += bytes_written;  
        buflen -= bytes_written;
    }

    return 0;
}

int sendStr(int fd, const string &s)
{
    return sendRaw(fd, s.c_str(), s.length());
}

...

struct stat s;
fstat(in, &s);
off_t fileLength = s.st_size;

char buf[BUFSIZE];
int bytes_read, bytes_written;

if ((vrsn == "1.1") || (vrsn == "1.0")) {
    ostringstream msg;
    msg << "HTTP/1.0 200 OK\r\n"
        << "Content-Type:" << fileExt << "\r\n"
        << "Content-Length: " << fileLength << "\r\n"
        << "Connection: close\r\n"
        << "\r\n";
    sendStr(fd, msg.str());
}

while (fileLength > 0) {
    bytes_read = read(in, buf, min(fileLength, BUFSIZE));
    if (bytes_read <= 0) break;
    if (sendRaw(fd, buf, bytes_read) == -1) break;
    fileLength -= bytes_read;  
}

close(fd);

答案 1 :(得分:2)

write(fd, msg.c_str(), strlen(msg.c_str())); - 您是否认为图像可能包含空(零)字节?因此将其视为C风格的字符串并不是一个好主意。

您应该发送原始数据并写入该数据的大小 - 直到第一个空字节为止