我的任务是实现简单的 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 大小的块。当我打开页面时出现问题enter image description here
页面显示不正确。我还设置了 Transfer-Encoding: chunked
strcpy(buf, ENCODING);
send(sock, buf, strlen(buf), 0);
ENCODING 被定义为“Transfer-Encoding: chunked\r\n”