我当时正在考虑使用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。
Edit:感谢评论,我解决了这个问题(请参见下面的代码)。欢迎指出代码中的任何改进或问题。
谢谢!
好吧,看起来格式和标题毕竟都是正确的。在发送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 HTTP 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 HTTP Response
send(client, finished_response.c_str(), finished_response.length(), 0); // flag = 0