HTML响应格式不正确?

问题描述 投票:0回答:1

我当时正在考虑使用C ++创建WebServer。我跟随this tutorial之后是Sloan Kelly,并在此引用了this answer

我编写了以下代码(仅显示发送部分):

std::stringstream make_response;
make_response << "HTTP/1.1 200 OK\r\n";
make_response << "Cache-Control: no-cache, private\r\n";
make_response << "Content-Type: text/html\r\n";
make_response << "Content-Length: 88\r\n";
make_response << "\r\n";
make_response << "Hello!";
std::string finished_response = make_response.str();

send(client, finished_response.c_str(), finished_response.length()+1, 0);

这里是什么问题?当我连接到127.0.0.1:8000时,屏幕完全空白。

我知道请求已经到达我,因为我已经在控制台中将其打印出来:

C:\Users\Jaideep Shekhar\OneDrive\Documents\Projects\ProjectC++\Library\v0.1\main>webserver.exe
Listening for incoming connections...
Client connected!
Client says: GET / HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36
Sec-Fetch-Mode: navigate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: cross-site
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

@_M
Client disconnected.

您可以从here复制整个源代码并打开终端:

g++ webserver.cpp -o webserver.exe -lws2_32 && webserver.exe

请注意,此代码适用于Windows OS。

c++ sockets httpresponse
1个回答
0
投票

好吧,看起来格式和标题毕竟都是正确的。在发送5字节的同时,我正在发送88字节的内容,这是我的错。

实际上,为避免这些问题,我现在将HTML放在其单独的文件中。

相关部分现在看起来像这样:

// Transfer the whole HTML to a std::string
std::fstream grab_content("home.html");
std::stringstream make_content;
make_content << grab_content.rdbuf();
std::string finished_content;
finished_content = make_content.str();

// Create the HTML Response
std::stringstream make_response;
make_response << "HTTP/1.1 200 OK\r\n";
make_response << "Cache-Control: no-cache, private\r\n";
make_response << "Content-Type: text/html\r\n";
make_response << "Content-Length: " << finished_content.length() << "\r\n";
make_response << "\r\n";
make_response << finished_content;
// Transfer it to a std::string to send
std::string finished_response = make_response.str();

// Send the HTML Response
send(client, finished_response.c_str(), finished_response.length(), 0);  // flag = 0
© www.soinside.com 2019 - 2024. All rights reserved.