gpt4 book ai didi

c - 通过 Linux C TCP 发送图像

转载 作者:行者123 更新时间:2023-11-30 20:11:24 25 4
gpt4 key购买 nike

我正在尝试使用纯 C 语言编写的简单 HTTP 服务器来维持与浏览器的持久连接。

对任何 HTML/文本的响应都很好,但我在发送图像文件时遇到问题。我意识到,当浏览器连接时, header (即由于 content-length)是必需的。因此,我首先发送 header ,然后发送图像。服务器端代码如下:

    // 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() 发送 header ,并使用 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";

最佳答案

您没有展示如何创建 header ,但您必须意识到在 C 中,字符串以 0x00 结尾:

header-field: value\n\0x00

您可能没有发送

header-field: value\nIMAGEDATA

但是

header-field: value\n\0x00IMAGEDATA

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

关于c - 通过 Linux C TCP 发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40706363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com