gpt4 book ai didi

分块传输编码 - 页面显示不正确

转载 作者:可可西里 更新时间:2023-11-01 17:26:00 26 4
gpt4 key购买 nike

我的任务是实现简单的 HTTP 服务器。当我发送响应时,我应该支持分块传输编码。这是我向客户端发送响应的函数。

static int serve_request(int sock, struct conf_arg *arg, char version[])
{
FILE *html = NULL;
char buf[MAX_MSG];

strcat(arg->root, arg->defdoc);
html = fopen(arg->root, "r");
if (!html) {
not_found(sock, version);
return 0;
}
good_responce(sock, version);
do {
fgets(buf, sizeof(buf), html);
const unsigned chunk = CHUNK_SIZE;
char *pbuf = buf;
char tempbuf[chunk + 10];

while (strlen(pbuf) >= chunk) {
sprintf(tempbuf, "%x\r\n", chunk);
write(sock, tempbuf, strlen(tempbuf));
write(sock, pbuf, chunk);
pbuf += chunk;
strcpy(tempbuf, "\r\n");
write(sock, tempbuf, strlen(tempbuf));
}
if (strlen(pbuf) == 0) {
sprintf(tempbuf, "%x\r\n", 0);
write(sock, tempbuf, strlen(tempbuf));
}
if (strlen(pbuf) > 0) {
sprintf(tempbuf, "%x\r\n", (unsigned)strlen(pbuf));
write(sock, tempbuf, strlen(tempbuf));
write(sock, pbuf, strlen(pbuf));
sprintf(tempbuf, "%x\r\n", 0);
write(sock, tempbuf, strlen(tempbuf));
}
strcpy(tempbuf, "\r\n");
write(sock, tempbuf, strlen(tempbuf));
} while (!feof(html));
fclose(html);
return 0;
}

CHUNK_SIZE 被定义为 1024,因为我想发送 1KB 大小的 block 。当我打开页面时出现问题 enter image description here页面显示不正常。我还设置了 Transfer-Encoding: chunked

strcpy(buf, ENCODING);
send(sock, buf, strlen(buf), 0);

ENCODING 定义为“Transfer-Encoding: chunked\r\n”

最佳答案

我想我知道问题出在哪里,但不完全确定。

在您的do 循环中,您会得到一个充满数据的buf 并发送它。然后你得到另一个充满数据的缓冲区并发送它。但是在发送了每个数据缓冲区之后,您可以通过发送 0\r\n终止传输。例如:

1024    // send first chunk
1024 // send second chunk
256 // last part of first bufer
0 // terminate transfer
1024 // send first chunk of second buffer
1024 //...
256
0

虽然在发送最后一个 block 之前再次填充缓冲区可能更好(使用 memmove 将最后一部分向下移动,然后调用 fgets 填充剩余部分) ,您可能会通过仅在 do ... while 循环之后发送 0\r\n 来“保存”,例如:

        if (strlen(pbuf) > 0) {
sprintf(tempbuf, "%x\r\n", (unsigned)strlen(pbuf));
write(sock, tempbuf, strlen(tempbuf));
write(sock, pbuf, strlen(pbuf));
//sprintf(tempbuf, "%x\r\n", 0);
//write(sock, tempbuf, strlen(tempbuf));
}
//strcpy(tempbuf, "\r\n");
//write(sock, tempbuf, strlen(tempbuf));
} while (!feof(html));
sprintf(tempbuf, "%x\r\n", 0);
write(sock, tempbuf, strlen(tempbuf));
strcpy(tempbuf, "\r\n");
write(sock, tempbuf, strlen(tempbuf));

还请注意,您必须检查fgets 的结果,因为它可以在eof 上返回零;缓冲区不会被刷新,你将再次发送最后一部分:

    if (fgets(buf, sizeof(buf), html)==NULL) break;

另请参阅有关您不必要地使用 tempbuf 的评论。

关于分块传输编码 - 页面显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47390582/

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