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

更强更鲁更棒!

相关推荐
无限进步_3 分钟前
【C++&string】寻找字符串中第一个唯一字符:两种经典解法详解
开发语言·c++·git·算法·github·哈希算法·visual studio
bukeyiwanshui6 分钟前
20260407 网络时间设置
网络
@insist1236 分钟前
网络工程师-因特网与网络互联(一):IPv4 协议精讲,从分类地址到子网划分
网络·网络工程师·软考·软件水平考试
taxunjishu12 分钟前
Profinet转MODBUS TCP在精细化工塔讯工业自动化中的应用方案
网络·网络协议
木下~learning15 分钟前
零基础Git入门:Linux+Gitee实战指南
linux·git·gitee·github·虚拟机·版本控制·ubunt
不愿透露姓名的大鹏15 分钟前
MySQL Binlog配置优化全攻略
运维·服务器·数据库·mysql·adb
hzxpaipai17 分钟前
英语+越南语网站架构设计:派迪科技多语言建站实践解析
网络·科技·物联网·网络安全·https
安科瑞小许26 分钟前
35kV变电站的“智慧大脑”——综合自动化系统
大数据·网络·变电站·零碳园区
IMPYLH26 分钟前
Linux 的 mkdir 命令
linux·运维·服务器·bash
yy_xzz29 分钟前
【Linux开发】多线程并发服务器(网络编程+多线程+线程同步实现的聊天服务器和客户端)
linux·服务器·网络