通过Linux C TCP发送图像

时间:2016-11-20 16:19:21

标签: c linux sockets tcp tcpserver

我试图通过用纯C编写的简单HTTP服务器来维护浏览器的持久连接。

对任何HTML /文本的响应都很好,但我在发送图像文件时遇到问题。我已经意识到当浏览器连接时必须使用标题(即因为content-length)。因此,我首先发送标题,然后发送图像。服务器代码是这样的:

    // section relating to responding an image
else if(!strncmp(buf, "GET /testpic.jpg", 16)) {
    FILE * _fdimg = fopen("testpic.jpg", "rb");
    struct stat st;
    stat("testpic.jpg", &st);

    char send_buffer[100000];

    int read_size = fread(send_buffer, 1, st.st_size ,  _fdimg);
    // regradless of the third param, the read_size value is 50029 which is the correct size of the image 


    // header_image is a char[] corresponding to appropriate headers with correct content-length

    write(socket, header_img, sizeof(header_img));
    write(socket, send_buffer, st.st_size);

    // This works, but I can't send the header with this function.
    // sendfile(socket, _fdimg, NULL, 600000);
}

现在浏览器将了解持久连接,将从套接字中获取正确数量的数据,但通过套接字发送的文件有一个小问题,在开头有一个额外的00(十六进制格式)

enter image description here

有什么建议吗?

注意:我还尝试使用正常write()发送标头,并使用sendfile()系统调用发送图像,但浏览器无法正确识别此标题,并且页面将继续加载

注意:图像大小为50028字节。 st.st_size和read_size值都是正确的,并且等于实际文件大小。我认为从文件中读取的过程是正常的,但是当我将其复制到缓冲区时,存在索引不匹配或某种错误。

更新标题:

char header_img[]=
"HTTP/1.1 200 OK\r\n"
"Connection: keep-alive\r\n"
"Content-Type:image/jpg\r\n"
"Content-Length: 50029\r\n\r\n";

1 个答案:

答案 0 :(得分:2)

您没有展示如何创建标题,但您必须意识到在C中,字符串为0x00 - 终止:

header-field: value\n\0x00

你可能没有发送

header-field: value\nIMAGEDATA

但是

header-field: value\n\0x00IMAGEDATA

因为你发送了整个字符串,而不仅仅是它的实际非终结符字符。