我正在编写一个 HTTP 服务器,但在发送较大的文件时遇到问题。如果我用 netcat 抓取它们,输出看起来很完美。如果我使用浏览器或 wget,有时我只能得到完整的文件。 WGET 不断收到“连接被对等方重置”错误,请参阅下面的输出。 Firefox 显示“连接已重置”。
下面是向客户端发送数据的相关流程:
int handle_request(int sockfd, struct cached_file content) {
char buffer[1024]; // FIXME hardcoded arbitrary buffer size for header
unsigned int sent_bytes;
unsigned int total = 0;
unsigned int bytes_left = content.size;
printf("I have to send %u bytes of content.\n", content.size);
snprintf(buffer, 1024, "HTTP/1.1 %s\nContent-Type: %s\nContent-Length: %s\n\n", content.statuscode, content.contenttype, content.sizestring);
sent_bytes = send(sockfd, buffer, strlen(buffer), MSG_MORE);
printf("I wanted to send %u bytes of header, and I sent %u.\n", strlen(buffer), sent_bytes);
while (total < bytes_left) {
sent_bytes = send(sockfd, content.data+total, bytes_left, 0);
if (sent_bytes == -1) {
printf("send() returned -1\n");
break;
}
total += sent_bytes;
bytes_left -= sent_bytes;
}
printf("I sent %u bytes of content. I had %u left to send.\n", total, bytes_left);
if (sent_bytes == -1)
logprint("socket error!", errno);
}
这是 wget 尝试获取文件的输出:
wget --tries 1 http://localhost:8081/image.jpg
--2015-07-01 13:21:42-- http://localhost:8081/image.jpg
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:8081... failed: Connection refused.
Connecting to localhost (localhost)|127.0.0.1|:8081... connected.
HTTP request sent, awaiting response... 200 OK
Length: 700895 (684K) [image/jpeg]
Saving to: ‘image.jpg.10’
image.jpg.10 53%[===============================> ] 363.31K --.-KB/s in 0.001s
2015-07-01 13:21:42 (688 MB/s) - Read error at byte 372031/700895 (Connection reset by peer). Giving up.
wget --tries 1 http://localhost:8081/image.jpg
--2015-07-01 13:21:43-- http://localhost:8081/image.jpg
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:8081... failed: Connection refused.
Connecting to localhost (localhost)|127.0.0.1|:8081... connected.
HTTP request sent, awaiting response... 200 OK
Length: 700895 (684K) [image/jpeg]
Saving to: ‘image.jpg.11’
image.jpg.11 6%[==> ] 42.69K --.-KB/s in 0s
2015-07-01 13:21:43 (500 MB/s) - Read error at byte 43711/700895 (Connection reset by peer). Giving up.
调试 http 服务器的输出:
I have to send 700895 bytes of content.
I wanted to send 65 bytes of header, and I sent 65.
I sent 700895 bytes of content. I had 0 left to send.
我希望能有另一双眼睛来关注此事!为什么会发生这种情况以及如何解决它?