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 池化层
是什么:池化层跟卷积层类似有个滑动窗口,用来取一个区域内的最大值或者平均值。 作用:卷积神经网络的最后的部分应该要看到整个图像的全局,通过池化(汇聚)操作,逐渐汇聚要取的像素,最终实现学习全局表示的…...
ChatGPT资源宝库:从提示工程到项目实践的完整指南
1. 项目概述:一份关于ChatGPT的“Awesome”清单意味着什么?如果你最近在GitHub上搜索过任何与ChatGPT、AI或提示工程相关的内容,那么你大概率见过一个以“awesome-”开头的仓库。而sindresorhus/awesome-chatgpt无疑是这个领域里最知名、最常…...
Allegro 16.6 高效布线实战:Region规则、Xnet等长与模块复用的进阶技巧
Allegro 16.6 高效布线实战:Region规则、Xnet等长与模块复用的进阶技巧 在高速PCB设计领域,Allegro 16.6作为行业标杆工具,其深度功能往往决定了设计效率的天花板。当面对BGA封装密度突破1000pin、信号速率迈入10Gbps时代的复杂主板时&#x…...
罗技PUBG鼠标宏终极教程:告别压枪烦恼,轻松提升射击稳定性
罗技PUBG鼠标宏终极教程:告别压枪烦恼,轻松提升射击稳定性 【免费下载链接】logitech-pubg PUBG no recoil script for Logitech gaming mouse / 绝地求生 罗技 鼠标宏 项目地址: https://gitcode.com/gh_mirrors/lo/logitech-pubg 还在为《绝地求…...
PCL2启动器离线登录按钮消失?5分钟快速修复指南
PCL2启动器离线登录按钮消失?5分钟快速修复指南 【免费下载链接】PCL Minecraft 启动器 Plain Craft Launcher(PCL)。 项目地址: https://gitcode.com/gh_mirrors/pc/PCL 你是否遇到过PCL2启动器离线登录按钮突然消失的困扰࿱…...
开源PCB自动布线神器FreeRouting:5分钟上手,效率提升300%
开源PCB自动布线神器FreeRouting:5分钟上手,效率提升300% 【免费下载链接】freerouting Advanced PCB auto-router 项目地址: https://gitcode.com/gh_mirrors/fr/freerouting FreeRouting是一款功能强大的开源PCB自动布线工具,它能帮…...
Docker Compose编排微服务
Docker Compose编排微服务 引言 Docker Compose是Docker官方提供的容器编排工具,用于定义和运行多容器Docker应用。通过Compose,可以使用YAML文件定义服务、网络、数据卷等资源,然后通过简单的命令启动和停止整个应用。Docker Compose特别适合…...
MySQL-MVCC核心原理-版本链ReadView与可见性判断
MVCC 全称是 Multi-Version Concurrency Control,也就是多版本并发控制。它的核心思想是:为同一行数据维护多个版本,让读写在很多情况下不用互相阻塞。 没有 MVCC 时,读写冲突通常要大量依赖锁。MVCC 让普通 select 可以读一个可见…...
体育科学论文降AI工具免费推荐:2026年体育科学研究毕业论文知网AIGC超标4.8元亲测达标完整指南
体育科学论文降AI工具免费推荐:2026年体育科学研究毕业论文知网AIGC超标4.8元亲测达标完整指南 帮同学选过降AI工具,综合价格、效果、保障来看,推荐嘎嘎降AI(www.aigcleaner.com)。 4.8元,达标率99.26%&a…...
FTDI Friend:从USB转串口到AVR编程的嵌入式开发利器
1. 项目概述:为什么你需要一个FTDI Friend?在嵌入式开发和单片机玩家里,串口通信就像空气和水一样基础且不可或缺。无论是给Arduino上传代码,还是让树莓派和传感器模块“说上话”,亦或是调试一个自己焊的STM32最小系统…...
免费开源字体编辑器终极指南:5个核心模块带你从零到专业设计
免费开源字体编辑器终极指南:5个核心模块带你从零到专业设计 【免费下载链接】fontforge Free (libre) font editor for Windows, Mac OS X and GNULinux 项目地址: https://gitcode.com/gh_mirrors/fo/fontforge 想要免费编辑字体却找不到合适的工具&#x…...
