为什么我的服务器只将文件的第一行写到我的客户端?

Why does my server only write the first line of a file to my client?

我有两个程序,一个简单的客户端和一个简单的服务器,我正在尝试从我的客户端向我的服务器发送 HTTP GET 请求。在这种情况下,我从我的客户端向我的服务器发送一个 GET /index.html HTTP/1.1\r\n\r\n 请求,我让服务器将 index.html 的内容发送到我的客户端,以便它输出到 stdout。我已经设法完成了大部分工作,除了客户端仅将我的 index.html 文件的第一行输出到 stdout,我就是不明白为什么。令我困惑的是,与此相反,我的服务器程序中的 printf() 正在打印整个 index.html。这是服务器程序的片段:

#include "csapp.h"

int MAXLEN = 10000;
int main(int argc, char* argv[]){

       //some initializations and other things

        if(( in = fopen(req, "r")) == NULL){
            rio_writen(connfd, "Couldn't open file\n", MAXLEN);
            exit(0);
        }
        while (fgets(output, 99999, in) != NULL){
            printf("%s", output); //printing entire thing
            write(connfd, output, sizeof(output)); //should write entire file!

        }
        fclose(in);
        Close(connfd);
    }
    exit(0);
}

为了以防万一,从我的客户端程序,这是我的客户端从我的服务器读取的方式,尽管我怀疑这是问题发生的地方,例如,我可以阅读整个 index.html来自 wwww.google.com 很好,这让事情变得更加混乱。

int n = Rio_readlineb(&reeo, buffer, MAXLEN);
while(n > 0){
    printf("%s", buffer);
    n = Rio_readlineb(&reeo, buffer, MAXLEN);
}
Close(fd);
exit(0);

如果有人能告诉我出了什么问题,我将不胜感激。另外,csapp.c可以找到here.

将循环更改为:

    while (fgets(output, sizeof(output), in) != NULL){
        printf("%s", output); //printing entire thing
        write(connfd, output, strlen(output));
    }

您应该在从文件读取时使用 sizeof,以确保它不会尝试读取超过缓冲区大小的内容。但是在写的时候,你应该只写 buffer 中包含刚刚读取的行的部分。您的代码正在写入整个缓冲区,其中包括所有未初始化的字节。