【发布时间】:2018-05-06 09:26:14
【问题描述】:
我的任务是实现一个简单的 HTTP 服务器。我尝试打开一个通过 HTTP 下载的站点。我的服务器可以正确显示 html、css 和 js 文件,但无法显示图像(png、jpg)。我用 Wireshark 记录了这些响应数据包:
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked
.PNG
.
这也是我读取请求并向客户端发送响应的函数。
static int serve_request(int sock, struct conf_arg *arg, char version[])
{
FILE *html = NULL;
char buf[MAX_MSG];
const unsigned chunk = (unsigned)CHUNK_SIZE;
char *pbuf = NULL;
char tempbuf[CHUNK_SIZE + 3];
size_t len;
strcpy(buf, arg->root);
if(buf[strlen(buf) - 1] == '/')
strcat(buf, arg->defdoc);
html = fopen(buf, "rb");
if (!html) {
not_found(sock, version);
return -1;
}
good_responce(sock, version);
do {
if (fgets(buf, sizeof(buf), html) == NULL)
break;
pbuf = buf;
while ((len = strlen(pbuf)) != 0) {
if (len < chunk) {
//printf("LEN:%d\n", (int)len);
sprintf(tempbuf, "%x\r\n", (int)len);
write(sock, tempbuf, strlen(tempbuf));
write(sock, pbuf, strlen(pbuf));
//printf("%s", pbuf);
pbuf += len;
write(sock, "\r\n", 2);
} else {
sprintf(tempbuf, "%x\r\n", (int)chunk);
write(sock, tempbuf, strlen(tempbuf));
//strncpy(tempbuf, pbuf, chunk);
//printf("%d\n%s\n", (int)chunk, tempbuf);
write(sock, pbuf, chunk);
pbuf += chunk;
write(sock, "\r\n", 2);
}
}
} while (!feof(html));
strcpy(tempbuf, "0\r\n\r\n");
write(sock, tempbuf, strlen(tempbuf));
fclose(html);
return 0;
}
我不知道问题出在哪里,所以希望你能帮助我。
UPD:我将打开模式更改为 rb,但没有帮助。我在 Wireshark 中得到相同的输出。
【问题讨论】:
-
您正在以文本模式打开文件,这可能是问题所在。
-
我应该使用什么模式?
-
二进制模式。这很可能是问题
-
二进制,当然?
-
是的,一般来说,任何带有 strlen() 的网络代码都会被破坏。