【发布时间】:2016-11-20 16:19:21
【问题描述】:
我正在尝试通过一个用纯 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(十六进制格式)
有什么建议吗?
注意:我也尝试发送带有正常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";
【问题讨论】:
-
为什么内存从
send_buffer移动到send_buffer?那应该什么都不做。 -
显然,有必要显示您将标题发送/创建的位置。
-
@MarcusMüller 是的,
memmove行只是我测试过但忘记删除的东西。我将在几秒钟内使用标题和浏览器登录进行编辑。
标签: c linux sockets tcp tcpserver