【发布时间】:2016-02-20 00:02:22
【问题描述】:
我有两个程序,一个简单的客户端和一个简单的服务器,我正在尝试将 HTTP GET 请求从我的客户端发送到我的服务器。在这种情况下,我从客户端向服务器发送GET /index.html HTTP/1.1\r\n\r\n 请求,然后服务器将index.html 的内容发送给客户端,以输出到stdout。我已经设法完成了大部分工作,除了客户端只将我的index.html 文件的第一行输出到stdout,我就是不明白为什么。令我困惑的是,与此相反,我的服务器程序中的printf() 正在打印整个index.html。这是来自服务器程序的 sn-p:
#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);
}
以防万一,从我的客户端程序中,这是我的客户端从我的服务器读取的方式,尽管我怀疑这是问题所在,例如,我可以从wwww.google.com 中读取整个index.html很好,这让事情变得更加混乱。
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找到。
【问题讨论】:
-
output的声明是什么? -
fgets()只返回文件中的一行。write(connfd, output, sizeof(output))将尝试写入整个output数组,而不仅仅是使用fgets读取的数量。你应该使用strlen(output)。 -
@Barmar In main, char output[9999];
-
所以即使一行只有 10 个字符,你每次也要写 9999 个字符。
-
您可能想了解
sendfile()。
标签: c file-io network-programming server client