【计算机网络】mini HTTP服务器框架与代码

注注注:本篇博文都是代码实现细节,但不会进行演示,演示看孪生篇

另外,由于tcp套接字部分本质都是套路,所以就不再进行赘述。

目录

  • [1 请求反序列化](#1 请求反序列化)
  • [2 读取url文件内容](#2 读取url文件内容)
  • [3 构建响应](#3 构建响应)

1 请求反序列化

我们肯定会先收到请求(可以由浏览器,telnet等等进行模拟)

注意到请求格式如下图,因此我们需要先封装一个request方便操作t

因此按照格式分为基本的下部分。

cpp 复制代码
class Request
{
private:
	std::string _request_line;
	std::vector<std::string> _request_headers;
	std::string _blank;
	std::string _data;
};

再在类中设置一个公有方法反序列即可。

由于我们请求的每一行都有/r/b,因此我们先设计出提取每一行的函数,然后提取出每一行再逐个分解

注意其中的basic_sep是/r/b,也正是每一行的分隔符。

且当前行未有分隔符时返回空,为空行时返回空行,否则正常返回除分隔符外的当前行。

这里可以自由控制。

c 复制代码
std::string Getline(std::string &message)
{
    auto pos = message.find(basic_sep);
    if (pos == std::string::npos)
    {
        return {};
    }
    std::string result = message.substr(0, pos);
    message.erase(0, pos + basic_sep.size());

    return result.size() == 0 ? basic_sep : result;
}

在对每一行进行处理

cpp 复制代码
// 基本的反序列化
_request_line = Getline(message);
std::string header;
while ((header = Getline(message)) != basic_sep && !header.empty())
{
    _request_headers.push_back(header);
}
_data = message;

注意只有当前获取的header不为分隔符并且不为空时才可以push到我们的_request_headers,最后将剩余部分赋值给正文即可。

由此我们便得到的基本的数据格式,接下来是细分:

将请求行中的方法,url,版本,各个使用一个变量进行存储,以及报头部分可以hash进行对应,方便存取。

cpp 复制代码
std::string _method;
std::string _url;
std::string _version;
std::unordered_map<std::string, std::string> _request_headers_kv;
std::string _path;// 拼接上rootpath后的路径,为当前工作目录下的前端起始目录

对于请求行的url分割时需要注意:当路径最后一个元素是'/'时,那么就代表当前页面是一个目录,因此需要拼接上一个当前目录的默认页面。就如上图一样。

浏览器会将域名解释为IP在自动拼接上端口号,总体的格式类似IP:port,故默认url就是'/',所以当访问一个目录时总得有个目标吧,因此拼上当前目录的首页即可,也就是index.html。

大多数的网站首页都是这个名字。

csharp 复制代码
void ParseReqLine(const std::string &ReqLine)
{
    std::stringstream in;
    in << ReqLine;
    in >> _method >> _url >> _version;

    _path = rootpath + _url;
    // _url的第一个/就是web根目录,因为我们会在服务端进行拼接,故他可以为任意linux下的某一路径,rootpath也就是为此准备的,同学们自行设置即可
    
    // 注意:当url目标为目录时,需要拼接homepage,否则你要全获取?
    if (_path[_path.size() - 1] == '/')
    {
        _path = _path + homepage;

    }
}
void ParseReqHeader(const std::vector<std::string> &ReqHeaders)
{
    for (auto &header : ReqHeaders)
    {
        auto pos = header.find(line_sep);
        if (pos == std::string::npos)
        {
            continue;
        }
        std::string key = header.substr(0, pos);
        std::string value = header.substr(pos + basic_sep.size());
        _request_headers_kv[key] = value;
    }
}

2 读取url文件内容

由于是超文本,因此需要二进制进行读取。

cpp 复制代码
std::string GetContent(std::string path)
{
    std::ifstream in(path, std::fstream::binary);
    if (!in.is_open())
    {
        return {};
    }
    in.seekg(0, std::ios::end);
    int filesize = in.tellg();
    in.seekg(0, std::ios::beg);

    std::string result;
    result.resize(filesize);
    in.read((char *)result.c_str(), filesize);

    in.close();

    return result;
}

3 构建响应

还是依照格式进行封装。

csharp 复制代码
std::string _version;
std::string _code;
std::string _desc;
std::unordered_map<std::string, std::string> _resp_headers_kv;
std::string _blank;
std::string _body;

接下来无非就是添加状态行,报头,正文部分,最后将其整合在一起进行序列化再发送。

cpp 复制代码
const static std::string basic_sep = "\r\n";
const static std::string line_sep = ": ";
const static std::string version = "HTTP/1.0";
const static std::string space_sep = " ";

class Response
{
public:
    Response() : _version(version), _blank(basic_sep)
    {
    }
    void AddCode(int code, std::string desc)
    {
        _code = std::to_string(code);
        _desc = desc;
    }
    void AddHeader(const std::string &key, const std::string &value)
    {
        // _resp_headers_kv[key] = value;
        _resp_headers_kv.insert(std::make_pair(key, value));
    }
    void AddBody(const std::string &body)
    {
        _body = body;
    }
    std::string Serialization()
    {
        std::string result;
        // add StatusLine
        result = _version + space_sep + _code + space_sep + _desc + basic_sep;
        // add Headers
        for (auto &header : _resp_headers_kv)
        {
            result += (header.first + line_sep + header.second + basic_sep);
        }
        // add blank
        result += _blank;
        // add body
        result += _body;

        return result;
    }
    ~Response()
    {
    }

private:
    // 基本
    std::string _version;
    std::string _code;
    std::string _desc;
    std::unordered_map<std::string, std::string> _resp_headers_kv;
    std::string _blank;
    std::string _body;
};

由此在我们的构建一下对应的响应即可

还有很多地方可以进行优化,但本质只是搞一个大概的框架。

完整代码详见Gitee!

更强更鲁更棒!

相关推荐
ZLRRLZ14 分钟前
【数据结构】二叉树进阶算法题
数据结构·c++·算法
hello 早上好14 分钟前
TCP/IP、SOCKET、HTTP
网络协议·tcp/ip·http
闻缺陷则喜何志丹17 分钟前
【并集查找】P4380 [USACO18OPEN] Multiplayer Moo S|省选-
数据结构·c++·洛谷·并集查找
情深不寿31719 分钟前
进程通信----匿名管道
linux·服务器·开发语言·c++
德育处主任21 分钟前
亚马逊云科技玩法:用 S3 + CloudFront,给你的静态网站上个全球 CDN 加速 ✈️
服务器·后端·cdn
hz_zhangrl21 分钟前
CCF-GESP 等级考试 2025年6月认证C++六级真题解析
c++·青少年编程·程序设计·gesp·gesp2025年6月·c++六级
1白天的黑夜138 分钟前
二分查找-153-寻找旋转排序数组中的最小值-力扣(LeetCode)
c++·leetcode·二分查找
孙尚香蕉1 小时前
HTTPS如何保障安全?详解证书体系与加密通信流程
网络协议·安全·https
国科安芯1 小时前
无人机电池通讯接口应用:CANFD工业级芯片的选型与技术要点
网络·单片机·嵌入式硬件·安全·硬件架构·无人机
菠萝炒饭pineapple-boss1 小时前
rancher使用rke在华为云多网卡的服务器上安装k8s集群问题处理
运维·服务器·网络