Ai
1 Star 0 Fork 0

Shawy/2023Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
HttpServer.cc 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
Shawy 提交于 2023-06-09 16:28 +08:00 . Modified HttpServer.cc
#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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/shawyxy/2023-linux.git
git@gitee.com:shawyxy/2023-linux.git
shawyxy
2023-linux
2023Linux
main

搜索帮助