简介
前面的几篇文章已经介绍了如何使用asio搭建高并发的tcp服务器,以及http服务器。但是纯手写http服务器太麻烦了,有网络库beast已经帮我们实现了。这一期讲讲如何使用beast实现一个http服务器。
连接类
我们先实现http_server函数
1 | void http_server(tcp::acceptor& acceptor, tcp::socket& socket) |
http_server中添加了异步接收连接的逻辑,当有新的连接到来时创建http_connection
,然后启动服务,新连接监听对端数据。接下来http_server继续监听对端的新连接。
连接类http_connection
里实现了start函数监听对端数据
1 | void start() |
处理读请求,将读到的数据存储再成员变量request_
中,然后调用process_request
处理请求
1 | void read_request() |
check_deadline
主要时用来检测超时,当超过一定时间后自动关闭连接,因为http请求时短链接
1 | void |
process_request
函数中区分请求的类型,进行不同类型的处理如post还是get请求
1 | void process_request() |
create_response
函数中解析了不同的路由处理get请求
1 | void |
create_post_response
处理了post请求中的一部分路由
1 | void create_post_response() { |
write_response
发送请求
1 | void write_response() |
总结
本文介绍了如何使用beast网络库实现http服务器
视频连接https://space.bilibili.com/271469206/channel/collectiondetail?sid=313101