当前位置: 首页 > news >正文

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

测试页面 this is a test

浏览器打开8080 端口
在这里插入图片描述

下载文件

直接可以下载文件,比如放入一个rar压缩文件,也就是完成了一个http file server,也是可以接收post 数据,后面可以自行扩展

websocket

可以看我另外一个文章boost bease websocket协议

相关文章:

boost beast http server 测试

boost beast http client boost http server boost beast 是一个非常好用的库&#xff0c;带上boost的协程&#xff0c;好很多东西是比较好用的&#xff0c;以下程序使用四个线程开启协程处理进入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 哈利·波特的考试

基础知识&#xff1a;&#xff08;最短路的前提都是在图中两条边之间的权值非定值&#xff09; &#xff08;一&#xff09;Dijkstra方法 算法实现&#xff1a; …...

vue2-vue项目中你是如何解决跨域的?

1、跨域是什么&#xff1f; 跨域本质是浏览器基于同源策略的一种安全手段。 同源策略&#xff08;sameoriginpolicy&#xff09;&#xff0c;是一种约定&#xff0c;它是浏览器最核心也是最基本的安全功能。 所谓同源&#xff08;即指在同一个域&#xff09;具有以下三个相同点…...

【Paper Reading】DETR:End-to-End Object Detection with Transformers

背景 Transformer已经在NLP领域大展拳脚&#xff0c;逐步替代了LSTM/GRU等相关的Recurrent Neural Networks&#xff0c;相比于传统的RNN&#xff0c;Transformer主要具有以下几点优势 可解决长时序依赖问题&#xff0c;因为Transformer在计算attention的时候是在全局维度进行…...

【rust/入门】windows安装rust gnu环境(折腾)

说在前面 首先说明&#xff0c;我是rust入门选手&#xff0c;之前都是在wsl写rust&#xff0c;突然想在windows下装下rust。windows版本&#xff1a;windows11 22H2原文换源 心路历程 看到教程我陷入了沉默&#xff0c;(官方推荐) 打开Microsoft C Build Tools我开始不解&…...

java面试---字符串相关内容

字符串 1. 什么是Java中的字符串池&#xff08;String Pool&#xff09;&#xff1f;2. String、StringBuilder和StringBuffer之间的区别是什么&#xff1f;3. 如何比较两个字符串的内容是否相等&#xff1f;4、equals和的区别5. String类有哪些常用的方法&#xff1f; 1. 什么…...

MYSQL进阶-事务的基础知识

1.什么是数据库事务&#xff1f; 就是把好几个sql语句打包成一个整体执行&#xff0c;要么全部成功&#xff0c;要么全部失败&#xff01;&#xff01;&#xff01; 事务是一个不可分割的数据库操作序列&#xff0c;也是数据库并发控制的基本单位&#xff0c;其执 行的结果必…...

【C++】C++面向对象,泛型编程总结篇(封装,继承,多态,模板)|(秋招篇)

文章目录 前言如何理解面向对象&#xff1f;如何理解泛型编程&#xff1f;C面向对象的三大特性是什么构造函数有哪几种&#xff1f;讲一下移动构造函数当我们定义一个类 系统会自动帮我们生成哪些函数&#xff1f;标题讲一下类中三类成员&#xff08;公有私有保护&#xff09;三…...

【Github】作为程序员不得不知道的几款Github加速神器

文章目录 背景推荐1&#xff1a;FastGithub推荐2&#xff1a;dev-sidecar推荐3&#xff1a;Watt Toolkit推荐4&#xff1a;篡改猴插件用户脚本1&#xff09;下载安装-->篡改猴 Tampermonkey 插件2&#xff09;下载安装-->Github 增强 - 高速下载 用户脚本 推荐5&#xff…...

react18之08自定义hook (简单的axios-get、修改浏览器title、localStorage、获取滚动条位置、img转换为base64)

目录 react18之自定义hook ()01&#xff1a;自定义一个 简单的axios hook 发起get请求useHttp.jsx使用useHttp hook效果 02&#xff1a;自定义一个 修改浏览器title hook03&#xff1a;自定义一个 localStorage(获取、存储、移除) hookuseLocalStorage.jsx使用hook效果 04&…...

对CommonJS、AMD、CMD、ES Module的理解

CommonJS 常用于&#xff1a;服务器端&#xff0c;node&#xff0c;webpack 特点&#xff1a;同步/运行时加载&#xff0c;磁盘读取速度快 语法&#xff1a; // 1. 导出&#xff1a;通过module.exports或exports来暴露模块 module.exports { attr1, attr2 } ex…...

JVM之类加载与字节码(二)

3. 编译期处理 什么是语法糖 所谓的 语法糖 &#xff0c;其实就是指 java 编译器把 *.java 源码编译为 *.class 字节码的过程中&#xff0c;自动生成 和转换的一些代码&#xff0c;主要是为了减轻程序员的负担&#xff0c;算是 java 编译器给我们的一个额外福利&#xff08;给…...

安装linux操作系统

安装虚拟机的步骤&#xff1a; 安装linux系统 之后开启虚拟机 之后重启&#xff0c;打开虚拟机&#xff0c;登录root账号...

【SpringBoot】知识

.第一个程序HelloWorld 项目创建方式&#xff1a;使用 IDEA 直接创建项目 1、创建一个新项目 2、选择spring initalizr &#xff0c; 可以看到默认就是去官网的快速构建工具那里实现 3、填写项目信息 4、选择初始化的组件&#xff08;初学勾选 Web 即可&#xff09; 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路由选择的因素&#xff1a; 1.OSPF路由的开销值&#xff1a;宽带参考值默认为100. COST1000/接口带宽。此时接口 带宽的值可更改&#xff0c;更改后只改变参考数值&#xff0c;带宽仍然为初始值。 注意&#xff1a;更改COST需要 在路由的入方向&#xff0c;数据的出方…...

5.kubeadm安装

文章目录 kubeadm部署环境初始化所有的节点安装Docker所有节点安装kubeadm&#xff0c;kubelet和kubectl初始化方法一&#xff0c;配置文件初始化方法二&#xff0c;命令初始化 网络插件node节点总结 证书过期方法一方法二总结 部署Dashboard kubeadm部署 环境初始化 ###所有…...

【雕爷学编程】Arduino动手做(180)---Seeeduino Lotus开发板2

37款传感器与执行器的提法&#xff0c;在网络上广泛流传&#xff0c;其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块&#xff0c;依照实践出真知&#xff08;一定要动手做&#xff09;的理念&#xff0c;以学习和交流为目的&am…...

6.5 池化层

是什么&#xff1a;池化层跟卷积层类似有个滑动窗口&#xff0c;用来取一个区域内的最大值或者平均值。 作用&#xff1a;卷积神经网络的最后的部分应该要看到整个图像的全局&#xff0c;通过池化(汇聚)操作&#xff0c;逐渐汇聚要取的像素&#xff0c;最终实现学习全局表示的…...

Umi-OCR:完全免费开源的离线OCR神器,3分钟快速上手文字识别

Umi-OCR&#xff1a;完全免费开源的离线OCR神器&#xff0c;3分钟快速上手文字识别 【免费下载链接】Umi-OCR OCR software, free and offline. 开源、免费的离线OCR软件。支持截屏/批量导入图片&#xff0c;PDF文档识别&#xff0c;排除水印/页眉页脚&#xff0c;扫描/生成二维…...

AI驱动博客平台CodeBlog-app:开发者技术分享的智能解决方案

1. 项目概述&#xff1a;一个为开发者而生的AI驱动博客平台最近在GitHub上看到一个挺有意思的开源项目&#xff0c;叫CodeBlog-ai/codeblog-app。光看名字&#xff0c;你可能会觉得这又是一个普通的博客系统&#xff0c;或者是一个AI写作工具。但当我深入去研究它的代码和设计理…...

量子私有信息检索(QPIR)技术解析与应用前景

1. 量子私有信息检索技术概述量子私有信息检索&#xff08;Quantum Private Information Retrieval, QPIR&#xff09;是密码学领域的一项突破性技术&#xff0c;它允许用户从数据库中检索特定条目而不泄露被查询的是哪个条目。这项技术的核心价值在于解决了隐私保护与数据获取…...

基于LLM与视觉模型融合的智能体框架:从原理到工业质检实践

1. 项目概述&#xff1a;当AI学会“看”与“想”最近在探索AI与视觉结合的落地场景时&#xff0c;我深度体验了landing-ai/vision-agent这个项目。它不是一个简单的图像识别工具&#xff0c;而是一个试图让AI具备“视觉推理”能力的智能体框架。简单来说&#xff0c;它让AI不仅…...

量子误差缓解:Bhattacharyya距离与保形预测的应用

1. 量子噪声与误差缓解的核心挑战在当前的NISQ&#xff08;Noisy Intermediate-Scale Quantum&#xff09;时代&#xff0c;量子计算机面临的最大障碍就是噪声和误差问题。这些噪声主要来源于量子比特与环境之间的相互作用、门操作的不完美性以及测量误差等。以一个典型的超导量…...

3个技巧让SD-PPP插件提升Photoshop设计效率300%

3个技巧让SD-PPP插件提升Photoshop设计效率300% 【免费下载链接】sd-ppp A Photoshop AI plugin 项目地址: https://gitcode.com/gh_mirrors/sd/sd-ppp 还在为Photoshop和AI工具之间的频繁切换而烦恼吗&#xff1f;每次都要导出PSD、上传到AI平台、等待生成、再导回Phot…...

韩国市场合规语音交付迫在眉睫!ElevenLabs韩文生成必须配置的4项GDPR+KCC隐私开关

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;韩国市场语音AI合规落地的紧迫性与战略意义 韩国《个人信息保护法》&#xff08;PIPA&#xff09;于2023年修订后&#xff0c;明确将语音生物特征数据列为“敏感信息”&#xff0c;要求语音AI系统在采集…...

Cesium动态泛光效果实战:手把手教你用d3kit插件打造炫酷城市光效(附完整代码)

Cesium动态泛光效果实战&#xff1a;手把手教你用d3kit插件打造炫酷城市光效&#xff08;附完整代码&#xff09; 当夜幕降临&#xff0c;城市天际线被霓虹灯勾勒出流动的轮廓&#xff0c;这种视觉冲击力正是现代三维可视化项目的灵魂所在。本文将带你用d3kit这个轻量级插件&am…...

Arm Neoverse CMN-700一致性网格网络架构与寄存器配置详解

1. Arm Neoverse CMN-700一致性网格网络架构解析 在现代多核处理器设计中&#xff0c;一致性网格网络&#xff08;Coherent Mesh Network&#xff09;已成为解决核间通信瓶颈的关键技术。Arm Neoverse CMN-700作为第二代一致性互连架构&#xff0c;相比前代CMN-600在拓扑灵活性…...

005 DevEco Studio OHPM同步404报错 解决文档

[cs]005 DevEco Studio OHPM同步404报错 解决文档 文档简介 本文解决鸿蒙开发中新建空白项目自动触发ohpm install时报错&#xff1a;ohos/hypium、ohos/hamock包404找不到、拉取依赖失败问题。 核心原则&#xff1a;不修改项目任何自带文件、不删除系统生成依赖、不改动业务代…...