我有很簡單的web服務器:簡單的C++ Web服務器發送錯誤頭
#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
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
有什麼不對?
當我加入睡眠(1)的頁面被顯示在瀏覽器1秒和我有一個錯誤,連接(在瀏覽器) – mitch
@米喬克拒絕。嘗試發送'Connection:close'而不是'Connection:Keep-Alive' –
仍然不起作用 – mitch