我的任务是使用分块传输编码实现简单的HTTP服务器。 这是读取请求并向客户端发送响应的函数。
static int serve_request(int sock, struct conf_arg *arg, char version[])
{
int html;
char buf[MAX_MSG];
const unsigned chunk = (unsigned)CHUNK_SIZE;
char tempbuf[CHUNK_SIZE + 3];
ssize_t size;
ssize_t bytes_read;
strcpy(buf, arg->root);
if(buf[strlen(buf) - 1] == '/')
strcat(buf, arg->defdoc);
html = open(buf, O_RDONLY);
if (html == -1) {
perror("Error in opening file");
not_found(sock, version);
return -1;
}
good_responce(sock, version);
size = lseek(html, 0, SEEK_END);
lseek(html, 0, SEEK_SET);
printf("SIZE:%d\n", (int)size);
bytes_read = read(html, buf, size);
while (bytes_read > chunk) {
sprintf(tempbuf, "%x\r\n", (int)chunk);
write(sock, tempbuf, strlen(tempbuf));
write(sock, buf, chunk);
write(sock, "\r\n", 2);
bytes_read -= chunk;
}
sprintf(tempbuf, "%x\r\n", (int)bytes_read);
printf("LAST PART:%d\n", (int)bytes_read);
write(sock, tempbuf, strlen(tempbuf));
write(sock, buf, bytes_read);
write(sock, "\r\n", 2);
strcpy(tempbuf, "0\r\n\r\n");
write(sock, tempbuf, strlen(tempbuf));
close(html);
return 0;
}
当我尝试使用我的服务器打开简单站点时,我收到错误:ERR_INVALID_CHUNKED_ENCODING。所以我希望你能帮我找到问题。