boost beast http server 测试
boost beast http client
boost http server
boost beast 是一个非常好用的库,带上boost的协程,好很多东西是比较好用的,以下程序使用四个线程开启协程处理进入http协议处理。协议支持http get 和 http post
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/config.hpp>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
#undef BOOST_BEAST_VERSION_STRING
#define BOOST_BEAST_VERSION_STRING "qbversion1.1"
// Return a reasonable mime type based on the extension of a file.
beast::string_view
mime_type(beast::string_view path)
{using beast::iequals;auto const ext = [&path]{auto const pos = path.rfind(".");if(pos == beast::string_view::npos)return beast::string_view{};return path.substr(pos);}();if(iequals(ext, ".htm")) return "text/html";if(iequals(ext, ".html")) return "text/html";if(iequals(ext, ".php")) return "text/html";if(iequals(ext, ".css")) return "text/css";if(iequals(ext, ".txt")) return "text/plain";if(iequals(ext, ".js")) return "application/javascript";if(iequals(ext, ".json")) return "application/json";if(iequals(ext, ".xml")) return "application/xml";if(iequals(ext, ".swf")) return "application/x-shockwave-flash";if(iequals(ext, ".flv")) return "video/x-flv";if(iequals(ext, ".png")) return "image/png";if(iequals(ext, ".jpe")) return "image/jpeg";if(iequals(ext, ".jpeg")) return "image/jpeg";if(iequals(ext, ".jpg")) return "image/jpeg";if(iequals(ext, ".gif")) return "image/gif";if(iequals(ext, ".bmp")) return "image/bmp";if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";if(iequals(ext, ".tiff")) return "image/tiff";if(iequals(ext, ".tif")) return "image/tiff";if(iequals(ext, ".svg")) return "image/svg+xml";if(iequals(ext, ".svgz")) return "image/svg+xml";return "application/text";
}// Append an HTTP rel-path to a local filesystem path.
// The returned path is normalized for the platform.
std::string
path_cat(beast::string_view base,beast::string_view path)
{if(base.empty())return std::string(path);std::string result(base);
#ifdef BOOST_MSVCchar constexpr path_separator = '\\';if(result.back() == path_separator)result.resize(result.size() - 1);result.append(path.data(), path.size());for(auto& c : result)if(c == '/')c = path_separator;
#elsechar constexpr path_separator = '/';if(result.back() == path_separator)result.resize(result.size() - 1);result.append(path.data(), path.size());
#endifreturn result;
}// This function produces an HTTP response for the given
// request. The type of the response object depends on the
// contents of the request, so the interface requires the
// caller to pass a generic lambda for receiving the response.
template<class Body, class Allocator,class Send>
void
handle_request(beast::string_view doc_root,http::request<Body, http::basic_fields<Allocator>>&& req,Send&& send)
{// Returns a bad request responseauto const bad_request =[&req](beast::string_view why){http::response<http::string_body> res{http::status::bad_request, req.version()};res.set(http::field::server, BOOST_BEAST_VERSION_STRING);res.set(http::field::content_type, "text/html");res.keep_alive(req.keep_alive());res.body() = std::string(why);res.prepare_payload();return res;};// Returns a not found responseauto const not_found =[&req](beast::string_view target){http::response<http::string_body> res{http::status::not_found, req.version()};res.set(http::field::server, BOOST_BEAST_VERSION_STRING);res.set(http::field::content_type, "text/html");res.keep_alive(req.keep_alive());res.body() = "The resource '" + std::string(target) + "' was not found.";res.prepare_payload();return res;};// Returns a server error responseauto const server_error =[&req](beast::string_view what){http::response<http::string_body> res{http::status::internal_server_error, req.version()};res.set(http::field::server, BOOST_BEAST_VERSION_STRING);res.set(http::field::content_type, "text/html");res.keep_alive(req.keep_alive());res.body() = "An error occurred: '" + std::string(what) + "'";res.prepare_payload();return res;};// Make sure we can handle the methodif (req.method() != http::verb::get &&req.method() != http::verb::head){if (req.method() == http::verb::post){std::cout << req.target() << std::endl;/* string body = req.body();std::cout << "the body is " << body << std::endl;*/std::string lines = req.body();std::cout << lines << std::endl;http::response<http::empty_body> res{ http::status::ok, req.version() };res.set(http::field::server, BOOST_BEAST_VERSION_STRING);res.set(http::field::content_type, mime_type("./"));res.content_length(0);res.keep_alive(req.keep_alive());return send(std::move(res));//return send(bad_request("Unknown HTTP-method"));}else{std::cerr << "unknown http method\n";return send(bad_request("Unknown HTTP-method"));}}// Request path must be absolute and not contain "..".if( req.target().empty() ||req.target()[0] != '/' ||req.target().find("..") != beast::string_view::npos)return send(bad_request("Illegal request-target"));// Build the path to the requested filestd::string path = path_cat(doc_root, req.target());if(req.target().back() == '/')path.append("index.html");// Attempt to open the filebeast::error_code ec;http::file_body::value_type body;body.open(path.c_str(), beast::file_mode::scan, ec);// Handle the case where the file doesn't existif(ec == beast::errc::no_such_file_or_directory)return send(not_found(req.target()));// Handle an unknown errorif(ec)return send(server_error(ec.message()));// Cache the size since we need it after the moveauto const size = body.size();// Respond to HEAD requestif(req.method() == http::verb::head){http::response<http::empty_body> res{http::status::ok, req.version()};res.set(http::field::server, BOOST_BEAST_VERSION_STRING);res.set(http::field::content_type, mime_type(path));res.content_length(size);res.keep_alive(req.keep_alive());return send(std::move(res));}// Respond to GET requesthttp::response<http::file_body> res{std::piecewise_construct,std::make_tuple(std::move(body)),std::make_tuple(http::status::ok, req.version())};res.set(http::field::server, BOOST_BEAST_VERSION_STRING);res.set(http::field::content_type, mime_type(path));res.content_length(size);res.keep_alive(req.keep_alive());return send(std::move(res));
}//------------------------------------------------------------------------------// Report a failure
void
fail(beast::error_code ec, char const* what)
{std::cerr << what << ": " << ec.message() << "\n";
}// This is the C++11 equivalent of a generic lambda.
// The function object is used to send an HTTP message.
struct send_lambda
{beast::tcp_stream& stream_;bool& close_;beast::error_code& ec_;net::yield_context yield_;send_lambda(beast::tcp_stream& stream,bool& close,beast::error_code& ec,net::yield_context yield): stream_(stream), close_(close), ec_(ec), yield_(yield){}template<bool isRequest, class Body, class Fields>voidoperator()(http::message<isRequest, Body, Fields>&& msg) const{// Determine if we should close the connection afterclose_ = msg.need_eof();// We need the serializer here because the serializer requires// a non-const file_body, and the message oriented version of// http::write only works with const messages.http::serializer<isRequest, Body, Fields> sr{msg};http::async_write(stream_, sr, yield_[ec_]);}
};// Handles an HTTP server connection
void
do_session(beast::tcp_stream& stream,std::shared_ptr<std::string const> const& doc_root,net::yield_context yield)
{bool close = false;beast::error_code ec;// This buffer is required to persist across readsbeast::flat_buffer buffer;// This lambda is used to send messagessend_lambda lambda{stream, close, ec, yield};for(;;){// Set the timeout.stream.expires_after(std::chrono::seconds(30));// Read a requesthttp::request<http::string_body> req;http::async_read(stream, buffer, req, yield[ec]);if(ec == http::error::end_of_stream)break;if(ec)return fail(ec, "read");// Send the responsehandle_request(*doc_root, std::move(req), lambda);if(ec)return fail(ec, "write");if(close){// This means we should close the connection, usually because// the response indicated the "Connection: close" semantic.break;}}// Send a TCP shutdownstream.socket().shutdown(tcp::socket::shutdown_send, ec);// At this point the connection is closed gracefully
}//------------------------------------------------------------------------------// Accepts incoming connections and launches the sessions
void
do_listen(net::io_context& ioc,tcp::endpoint endpoint,std::shared_ptr<std::string const> const& doc_root,net::yield_context yield)
{beast::error_code ec;// Open the acceptortcp::acceptor acceptor(ioc);acceptor.open(endpoint.protocol(), ec);if(ec)return fail(ec, "open");// Allow address reuseacceptor.set_option(net::socket_base::reuse_address(true), ec);if(ec)return fail(ec, "set_option");// Bind to the server addressacceptor.bind(endpoint, ec);if(ec)return fail(ec, "bind");// Start listening for connectionsacceptor.listen(net::socket_base::max_listen_connections, ec);if(ec)return fail(ec, "listen");for(;;){tcp::socket socket(ioc);acceptor.async_accept(socket, yield[ec]);if(ec)fail(ec, "accept");elsenet::spawn(acceptor.get_executor(),std::bind(&do_session,beast::tcp_stream(std::move(socket)),doc_root,std::placeholders::_1));}
}int main(int argc, char* argv[])
{auto const address = net::ip::make_address("0.0.0.0");auto const port = static_cast<unsigned short>(std::atoi("8080"));auto const doc_root = std::make_shared<std::string>("./");auto const threads = std::max<int>(1, std::atoi("4"));// The io_context is required for all I/Onet::io_context ioc{threads};// Spawn a listening portnet::spawn(ioc,std::bind(&do_listen,std::ref(ioc),tcp::endpoint{address, port},doc_root,std::placeholders::_1));// Run the I/O service on the requested number of threadsstd::vector<std::thread> v;v.reserve(threads - 1);for(auto i = threads - 1; i > 0; --i)v.emplace_back([&ioc]{ioc.run();});ioc.run();return EXIT_SUCCESS;
}
python post 测试
post 客户端
import json
import requests
import time
headers = {'Content-Type': 'application/json'}
data = {"projectname":"four screen","picnum":8,"memo":"test"
}
try:r = requests.post("http://127.0.0.1:8080/test", json=data, headers=headers)print(r.text)
except requests.exceptions.ConnectionError:print('connectionError')
time.sleep(1)

get
用浏览器就行,写一个http index.html
浏览器打开8080 端口

下载文件
直接可以下载文件,比如放入一个rar压缩文件,也就是完成了一个http file server,也是可以接收post 数据,后面可以自行扩展
websocket
可以看我另外一个文章boost bease websocket协议
相关文章:
boost beast http server 测试
boost beast http client boost http server boost beast 是一个非常好用的库,带上boost的协程,好很多东西是比较好用的,以下程序使用四个线程开启协程处理进入http协议处理。协议支持http get 和 http post #include <boost/beast/cor…...
Android 10.0 系统开启禁用adb push和adb pull传输文件功能
1.使用场景 在进行10.0的系统开发中,在一些产品中由于一些开发的功能比较重要,防止技术点外泄在出货产品中,禁用 adb pull 和adb push等命令 来获取系统system下的jar 和apk 等文件,所以需要禁用这些命令 2.系统开启禁用adb push和adb pull传输文件功能的分析 看了下系统…...
浙大数据结构第七周之07-图4 哈利·波特的考试
基础知识:(最短路的前提都是在图中两条边之间的权值非定值) (一)Dijkstra方法 算法实现: …...
vue2-vue项目中你是如何解决跨域的?
1、跨域是什么? 跨域本质是浏览器基于同源策略的一种安全手段。 同源策略(sameoriginpolicy),是一种约定,它是浏览器最核心也是最基本的安全功能。 所谓同源(即指在同一个域)具有以下三个相同点…...
【Paper Reading】DETR:End-to-End Object Detection with Transformers
背景 Transformer已经在NLP领域大展拳脚,逐步替代了LSTM/GRU等相关的Recurrent Neural Networks,相比于传统的RNN,Transformer主要具有以下几点优势 可解决长时序依赖问题,因为Transformer在计算attention的时候是在全局维度进行…...
【rust/入门】windows安装rust gnu环境(折腾)
说在前面 首先说明,我是rust入门选手,之前都是在wsl写rust,突然想在windows下装下rust。windows版本:windows11 22H2原文换源 心路历程 看到教程我陷入了沉默,(官方推荐) 打开Microsoft C Build Tools我开始不解&…...
java面试---字符串相关内容
字符串 1. 什么是Java中的字符串池(String Pool)?2. String、StringBuilder和StringBuffer之间的区别是什么?3. 如何比较两个字符串的内容是否相等?4、equals和的区别5. String类有哪些常用的方法? 1. 什么…...
MYSQL进阶-事务的基础知识
1.什么是数据库事务? 就是把好几个sql语句打包成一个整体执行,要么全部成功,要么全部失败!!! 事务是一个不可分割的数据库操作序列,也是数据库并发控制的基本单位,其执 行的结果必…...
【C++】C++面向对象,泛型编程总结篇(封装,继承,多态,模板)|(秋招篇)
文章目录 前言如何理解面向对象?如何理解泛型编程?C面向对象的三大特性是什么构造函数有哪几种?讲一下移动构造函数当我们定义一个类 系统会自动帮我们生成哪些函数?标题讲一下类中三类成员(公有私有保护)三…...
【Github】作为程序员不得不知道的几款Github加速神器
文章目录 背景推荐1:FastGithub推荐2:dev-sidecar推荐3:Watt Toolkit推荐4:篡改猴插件用户脚本1)下载安装-->篡改猴 Tampermonkey 插件2)下载安装-->Github 增强 - 高速下载 用户脚本 推荐5ÿ…...
react18之08自定义hook (简单的axios-get、修改浏览器title、localStorage、获取滚动条位置、img转换为base64)
目录 react18之自定义hook ()01:自定义一个 简单的axios hook 发起get请求useHttp.jsx使用useHttp hook效果 02:自定义一个 修改浏览器title hook03:自定义一个 localStorage(获取、存储、移除) hookuseLocalStorage.jsx使用hook效果 04&…...
对CommonJS、AMD、CMD、ES Module的理解
CommonJS 常用于:服务器端,node,webpack 特点:同步/运行时加载,磁盘读取速度快 语法: // 1. 导出:通过module.exports或exports来暴露模块 module.exports { attr1, attr2 } ex…...
JVM之类加载与字节码(二)
3. 编译期处理 什么是语法糖 所谓的 语法糖 ,其实就是指 java 编译器把 *.java 源码编译为 *.class 字节码的过程中,自动生成 和转换的一些代码,主要是为了减轻程序员的负担,算是 java 编译器给我们的一个额外福利(给…...
安装linux操作系统
安装虚拟机的步骤: 安装linux系统 之后开启虚拟机 之后重启,打开虚拟机,登录root账号...
【SpringBoot】知识
.第一个程序HelloWorld 项目创建方式:使用 IDEA 直接创建项目 1、创建一个新项目 2、选择spring initalizr , 可以看到默认就是去官网的快速构建工具那里实现 3、填写项目信息 4、选择初始化的组件(初学勾选 Web 即可) 5、填…...
react ant add/change created_at
1.引入ant的 Table import { Table, Space, Button, message } from antd; 2.获得接口的数据的时候增加上创建时间 const response await axios.get(${Config.BASE_URL}/api/v1/calculation_plans?token${getToken()});if (response.data.message ok) {const data respon…...
OSPF 动态路由协议 路由传递
影响OSPF路由选择的因素: 1.OSPF路由的开销值:宽带参考值默认为100. COST1000/接口带宽。此时接口 带宽的值可更改,更改后只改变参考数值,带宽仍然为初始值。 注意:更改COST需要 在路由的入方向,数据的出方…...
5.kubeadm安装
文章目录 kubeadm部署环境初始化所有的节点安装Docker所有节点安装kubeadm,kubelet和kubectl初始化方法一,配置文件初始化方法二,命令初始化 网络插件node节点总结 证书过期方法一方法二总结 部署Dashboard kubeadm部署 环境初始化 ###所有…...
【雕爷学编程】Arduino动手做(180)---Seeeduino Lotus开发板2
37款传感器与执行器的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的&am…...
6.5 池化层
是什么:池化层跟卷积层类似有个滑动窗口,用来取一个区域内的最大值或者平均值。 作用:卷积神经网络的最后的部分应该要看到整个图像的全局,通过池化(汇聚)操作,逐渐汇聚要取的像素,最终实现学习全局表示的…...
【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型
摘要 拍照搜题系统采用“三层管道(多模态 OCR → 语义检索 → 答案渲染)、两级检索(倒排 BM25 向量 HNSW)并以大语言模型兜底”的整体框架: 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后,分别用…...
多云管理“拦路虎”:深入解析网络互联、身份同步与成本可视化的技术复杂度
一、引言:多云环境的技术复杂性本质 企业采用多云策略已从技术选型升维至生存刚需。当业务系统分散部署在多个云平台时,基础设施的技术债呈现指数级积累。网络连接、身份认证、成本管理这三大核心挑战相互嵌套:跨云网络构建数据…...
论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(二)
HoST框架核心实现方法详解 - 论文深度解读(第二部分) 《Learning Humanoid Standing-up Control across Diverse Postures》 系列文章: 论文深度解读 + 算法与代码分析(二) 作者机构: 上海AI Lab, 上海交通大学, 香港大学, 浙江大学, 香港中文大学 论文主题: 人形机器人…...
渲染学进阶内容——模型
最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...
生成 Git SSH 证书
🔑 1. 生成 SSH 密钥对 在终端(Windows 使用 Git Bash,Mac/Linux 使用 Terminal)执行命令: ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" 参数说明: -t rsa&#x…...
【从零学习JVM|第三篇】类的生命周期(高频面试题)
前言: 在Java编程中,类的生命周期是指类从被加载到内存中开始,到被卸载出内存为止的整个过程。了解类的生命周期对于理解Java程序的运行机制以及性能优化非常重要。本文会深入探寻类的生命周期,让读者对此有深刻印象。 目录 …...
Selenium常用函数介绍
目录 一,元素定位 1.1 cssSeector 1.2 xpath 二,操作测试对象 三,窗口 3.1 案例 3.2 窗口切换 3.3 窗口大小 3.4 屏幕截图 3.5 关闭窗口 四,弹窗 五,等待 六,导航 七,文件上传 …...
Linux nano命令的基本使用
参考资料 GNU nanoを使いこなすnano基础 目录 一. 简介二. 文件打开2.1 普通方式打开文件2.2 只读方式打开文件 三. 文件查看3.1 打开文件时,显示行号3.2 翻页查看 四. 文件编辑4.1 Ctrl K 复制 和 Ctrl U 粘贴4.2 Alt/Esc U 撤回 五. 文件保存与退出5.1 Ctrl …...
GO协程(Goroutine)问题总结
在使用Go语言来编写代码时,遇到的一些问题总结一下 [参考文档]:https://www.topgoer.com/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine.html 1. main()函数默认的Goroutine 场景再现: 今天在看到这个教程的时候,在自己的电…...
[ACTF2020 新生赛]Include 1(php://filter伪协议)
题目 做法 启动靶机,点进去 点进去 查看URL,有 ?fileflag.php说明存在文件包含,原理是php://filter 协议 当它与包含函数结合时,php://filter流会被当作php文件执行。 用php://filter加编码,能让PHP把文件内容…...
