代码拉取完成,页面将自动刷新
#include "HttpServer.hpp"
#include <memory>
#include <fstream>
#include <vector>
#include "Util.hpp"
#define ROOT "./wwwroot" // web根目录
#define HOMEPAGE "index.htm" // 首页
void Usage(const std::string &proc)
{
std::cout << "\nUsage: " << proc << " [PORT]\n"
<< std::endl;
}
void HttpRequestHandler(int sockfd)
{
// 1. 读取请求
char buffer[10240];
ssize_t s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
if (s > 0)
buffer[s] = '\0';
// 2.0 准备响应
std::vector<std::string> vline;
Util::cutString(buffer, "\n", &vline);
std::vector<std::string> vblock;
Util::cutString(vline[0], " ", &vblock);
std::string file = vblock[1];
std::string target = ROOT;
if (file == "/")
file = "/index.html";
target += file;
std::cout << target << std::endl;
std::string content;
std::ifstream in(target);
if (in.is_open())
{
std::string line;
while (std::getline(in, line))
content += line;
in.close();
}
// 2.1 构建响应
std::string HttpResponse;
HttpResponse = "HTTP/1.1 200 OK\r\n";
HttpResponse += "\r\n";
HttpResponse += content;
// 3. 返回给客户端
send(sockfd, HttpResponse.c_str(), HttpResponse.size(), 0);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
Usage(argv[0]);
exit(1);
}
uint16_t port = atoi(argv[1]);
std::unique_ptr<HttpServer> server_ptr(new HttpServer(port, HttpRequestHandler));
server_ptr->Start();
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。