gpt4 book ai didi

c - 简单的 C++ Web 服务器发送错误的 header

转载 作者:行者123 更新时间:2023-11-30 17:39:23 25 4
gpt4 key购买 nike

我有非常简单的网络服务器:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>

char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Connection: Keep-Alive\r\n"
"Server: michal\r\n"
"Vary: Accept-Encoding\r\n"
"Keep-Alive: timeout=5, max=100\r\n\r\n"
"<html><body><h1>It works!</h1>"
"<p>This is the default web page for this server.</p>"
"<p>The web server software is running but no content has been added, yet.</p>"
"</body></html>\r\n";

int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);

int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");

setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);

if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}

listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
printf("got connection\n");

if (client_fd == -1) {
perror("Can't accept");
continue;
}

write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/
close(client_fd);
}
}

这在浏览器中有效,页面渲染正确,但当我进行 ab 测试时出现错误:

Benchmarking localhost (be patient)...apr_poll: The timeout specified has expired (70007)
Total of 2 requests completed

当我对本地主机(Apache)进行基准测试时,ab 工作正常

当我尝试使用 php file_get_contents 下载页面时,出现以下错误:

PHP Notice:  file_get_contents(): send of 2 bytes failed with errno=32 Broken pipe in /home/mitch/Dokumenty/projects/cpp/webserver/webserver/bench.php on line 7

出了什么问题?

最佳答案

我的猜测是,您在客户端有机会发送它想要的所有请求 header 之前终止连接。

因此在关闭之前添加延迟,或者在收到空行之前实际读取数据会有所帮助。

关于c - 简单的 C++ Web 服务器发送错误的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21830798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com