连接资源类封装 http 连接所需要的用户态资源,比如为每个 socket 分配读写缓冲区,请求解析结果等等。
在线程池中维护一个连接资源的容器,类需要为容器内的实例提供接口,实现报文解析、任务处理、和响应。
其中,报文解析用正则表达式标准库实现,可以复用正则匹配功能解析报文和配置文件等。
解析器类
解析请求报文
需要解析的条目:
- 请求行
- method
- url
- version
- 请求头
- linger
- host
- content-length
- 空行
- 请求体
- 用户名、密码
解析配置文件
采用最简单的规则,每行一个配置参数,格式如下:
1 | param = anything # comment |
空格、空行自动忽略。
非法格式处理
非法格式抛出异常。
其他
正则表达式对象可以理解为运行时“编译”,速度很慢,因此需要在系统启动时创建好所有对象。
需要完成的逻辑任务:
- 解析与 key 匹配的 val 并返回参数集合
- 检查无效格式,并反映结果,比如:请求行格式固定,解析出不识别的参数则返回 BAD_REQUEST
解析器对缓冲区内现有数据进行解析,可能的结果有:
- 请求格式有误,返回相应响应报文;
- 请求不完整,等待收到新的数据重新解析
- 请求无误,处理请求并相应请求
而解析器的任务只是给自己标识一个状态,剩下的由工作线程处理。
解析成功或者错误的数据都可以整段标记为失效,可覆盖。
连接资源类
连接资源类的每个实例都对应一个单独的连接套接字描述符,因此把每个实例的套接字描述符属性设为 const,在进行读写时如果需要重新注册 epoll 读写事件,需要调用 epoll 包装类的接口。由于系统启动时必须确定监听套接字描述符和连接套接字描述符的 epoll 触发模式,所以初始化 epoll 包装类时将相应类型写入唯一实例中。如此,连接资源便不需要写成模板类。