【计算机网络】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!

更强更鲁更棒!

相关推荐
懒人w38 分钟前
WebSocket 和 HTTP 请求区别
websocket·网络协议·http
金博客1 小时前
QT进行音频录制
c++·qt·音视频
TT-Kun1 小时前
C++ | vector 详解
开发语言·c++
何老生1 小时前
Linux之MySQL主从复制
linux·运维·mysql
ggdpzhk1 小时前
图片详解,最简单易懂!!!Ubuntu增强功能
linux·ubuntu
alsknv1 小时前
IP地址是怎么实现HTTPS访问的?
网络·网络协议·tcp/ip·安全·web安全·http·https
GDAL1 小时前
Puppeteer-Cluster:并行处理网页操作的新利器
运维·服务器·nodehtmltoimage
weixin_486681141 小时前
C++系列-STL中find相关的算法
java·c++·算法
limengshi1383921 小时前
通信工程学习:什么是GFP通用成帧规范
服务器·网络·网络协议·学习·信息与通信
做程序员的第一天1 小时前
计算机网络 ---- 计算机网络的体系结构【计算机网络的分层结构】
计算机网络