- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试使用此示例代码 boost beast advanced server example
它编译并运行良好。现在我想让它从给定的字符串中读取以回复 Get 或 Post 请求,而不是从文件中读取。
例如:客户端发送“www.xxxxxxxxxx.com/index.html”的Get请求程序将从数据库而非文件中获取的字符串回复请求。
我该怎么做?谢谢。
最佳答案
示例已经显示了它。看,例如关于如何生成错误响应:
// Returns a not found response
auto const not_found = [&req](boost::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 '" + target.to_string() + "' was not found.";
res.prepare_payload();
return res;
};
只需将 body()
设置为不同的值即可。
一个完整的演示,基本上只是从不需要的代码中剥离示例,并使用 prepare_payload
自动获取内容长度/编码。
#include <algorithm>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/config.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace http = boost::beast::http; // from <boost/beast/http.hpp>
namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp>
// This function produces an HTTP response for the given request.
template <class Body, class Allocator, class Send>
void handle_request(http::request<Body, http::basic_fields<Allocator> > &&req, Send &&send) {
// Returns a bad request response
auto const bad_request = [&req](boost::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() = why.to_string();
res.prepare_payload();
return res;
};
// Make sure we can handle the method
if (req.method() != http::verb::get)
return send(bad_request("Unsupported HTTP-method"));
// Request path must be absolute and not contain "..".
auto target = req.target();
if (target.empty() || target[0] != '/' || target.find("..") != boost::beast::string_view::npos)
return send(bad_request("Illegal request-target"));
http::response<http::string_body> res{ http::status::ok, req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.body() = "You're looking at " + target.to_string();
res.prepare_payload();
res.keep_alive(req.keep_alive());
return send(std::move(res));
}
// Report a failure
void fail(boost::system::error_code ec, char const *what) { std::cerr << what << ": " << ec.message() << "\n"; }
// Echoes back all received WebSocket messages
class websocket_session : public std::enable_shared_from_this<websocket_session> {
websocket::stream<tcp::socket> ws_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::steady_timer timer_;
boost::beast::multi_buffer buffer_;
public:
// Take ownership of the socket
explicit websocket_session(tcp::socket socket)
: ws_(std::move(socket)), strand_(ws_.get_executor()),
timer_(ws_.get_executor().context(), (std::chrono::steady_clock::time_point::max)()) {}
// Start the asynchronous operation
template <class Body, class Allocator> void run(http::request<Body, http::basic_fields<Allocator> > req) {
// Run the timer. The timer is operated
// continuously, this simplifies the code.
on_timer({});
// Set the timer
timer_.expires_after(std::chrono::seconds(15));
// Accept the websocket handshake
ws_.async_accept(req,
boost::asio::bind_executor(strand_, std::bind(&websocket_session::on_accept,
shared_from_this(), std::placeholders::_1)));
}
// Called when the timer expires.
void on_timer(boost::system::error_code ec) {
if (ec && ec != boost::asio::error::operation_aborted)
return fail(ec, "timer");
// Verify that the timer really expired since the deadline may have moved.
if (timer_.expiry() <= std::chrono::steady_clock::now()) {
// Closing the socket cancels all outstanding operations. They
// will complete with boost::asio::error::operation_aborted
ws_.next_layer().shutdown(tcp::socket::shutdown_both, ec);
ws_.next_layer().close(ec);
return;
}
// Wait on the timer
timer_.async_wait(boost::asio::bind_executor(
strand_, std::bind(&websocket_session::on_timer, shared_from_this(), std::placeholders::_1)));
}
void on_accept(boost::system::error_code ec) {
// Happens when the timer closes the socket
if (ec == boost::asio::error::operation_aborted)
return;
if (ec)
return fail(ec, "accept");
// Read a message
do_read();
}
void do_read() {
// Set the timer
timer_.expires_after(std::chrono::seconds(15));
// Read a message into our buffer
ws_.async_read(buffer_,
boost::asio::bind_executor(strand_, std::bind(&websocket_session::on_read, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)));
}
void on_read(boost::system::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
// Happens when the timer closes the socket
if (ec == boost::asio::error::operation_aborted)
return;
// This indicates that the websocket_session was closed
if (ec == websocket::error::closed)
return;
if (ec)
fail(ec, "read");
// Echo the message
ws_.text(ws_.got_text());
ws_.async_write(buffer_.data(),
boost::asio::bind_executor(strand_, std::bind(&websocket_session::on_write, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)));
}
void on_write(boost::system::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
// Happens when the timer closes the socket
if (ec == boost::asio::error::operation_aborted)
return;
if (ec)
return fail(ec, "write");
// Clear the buffer
buffer_.consume(buffer_.size());
// Do another read
do_read();
}
};
// Handles an HTTP server connection
class http_session : public std::enable_shared_from_this<http_session> {
// This queue is used for HTTP pipelining.
class queue {
enum {
// Maximum number of responses we will queue
limit = 8
};
// The type-erased, saved work item
struct work {
virtual ~work() = default;
virtual void operator()() = 0;
};
http_session &self_;
std::vector<std::unique_ptr<work> > items_;
public:
explicit queue(http_session &self) : self_(self) {
static_assert(limit > 0, "queue limit must be positive");
items_.reserve(limit);
}
// Returns `true` if we have reached the queue limit
bool is_full() const { return items_.size() >= limit; }
// Called when a message finishes sending
// Returns `true` if the caller should initiate a read
bool on_write() {
BOOST_ASSERT(!items_.empty());
auto const was_full = is_full();
items_.erase(items_.begin());
if (!items_.empty())
(*items_.front())();
return was_full;
}
// Called by the HTTP handler to send a response.
template <bool isRequest, class Body, class Fields>
void operator()(http::message<isRequest, Body, Fields> &&msg) {
// This holds a work item
struct work_impl : work {
http_session &self_;
http::message<isRequest, Body, Fields> msg_;
work_impl(http_session &self, http::message<isRequest, Body, Fields> &&msg)
: self_(self), msg_(std::move(msg)) {}
void operator()() {
http::async_write(self_.socket_, msg_,
boost::asio::bind_executor(
self_.strand_, std::bind(&http_session::on_write, self_.shared_from_this(),
std::placeholders::_1, msg_.need_eof())));
}
};
// Allocate and store the work
items_.emplace_back(new work_impl(self_, std::move(msg)));
// If there was no previous work, start this one
if (items_.size() == 1)
(*items_.front())();
}
};
tcp::socket socket_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::steady_timer timer_;
boost::beast::flat_buffer buffer_;
http::request<http::string_body> req_;
queue queue_;
public:
// Take ownership of the socket
explicit http_session(tcp::socket socket)
: socket_(std::move(socket)), strand_(socket_.get_executor()),
timer_(socket_.get_executor().context(), (std::chrono::steady_clock::time_point::max)()), queue_(*this) {}
// Start the asynchronous operation
void run() {
// Run the timer. The timer is operated
// continuously, this simplifies the code.
on_timer({});
do_read();
}
void do_read() {
// Set the timer
timer_.expires_after(std::chrono::seconds(15));
// Read a request
http::async_read(socket_, buffer_, req_,
boost::asio::bind_executor(
strand_, std::bind(&http_session::on_read, shared_from_this(), std::placeholders::_1)));
}
// Called when the timer expires.
void on_timer(boost::system::error_code ec) {
if (ec && ec != boost::asio::error::operation_aborted)
return fail(ec, "timer");
// Verify that the timer really expired since the deadline may have moved.
if (timer_.expiry() <= std::chrono::steady_clock::now()) {
// Closing the socket cancels all outstanding operations. They
// will complete with boost::asio::error::operation_aborted
socket_.shutdown(tcp::socket::shutdown_both, ec);
socket_.close(ec);
return;
}
// Wait on the timer
timer_.async_wait(boost::asio::bind_executor(
strand_, std::bind(&http_session::on_timer, shared_from_this(), std::placeholders::_1)));
}
void on_read(boost::system::error_code ec) {
// Happens when the timer closes the socket
if (ec == boost::asio::error::operation_aborted)
return;
// This means they closed the connection
if (ec == http::error::end_of_stream)
return do_close();
if (ec)
return fail(ec, "read");
// See if it is a WebSocket Upgrade
if (websocket::is_upgrade(req_)) {
// Create a WebSocket websocket_session by transferring the socket
std::make_shared<websocket_session>(std::move(socket_))->run(std::move(req_));
return;
}
// Send the response
handle_request(std::move(req_), queue_);
// If we aren't at the queue limit, try to pipeline another request
if (!queue_.is_full())
do_read();
}
void on_write(boost::system::error_code ec, bool close) {
// Happens when the timer closes the socket
if (ec == boost::asio::error::operation_aborted)
return;
if (ec)
return fail(ec, "write");
if (close) {
// This means we should close the connection, usually because
// the response indicated the "Connection: close" semantic.
return do_close();
}
// Inform the queue that a write completed
if (queue_.on_write()) {
// Read another request
do_read();
}
}
void do_close() {
// Send a TCP shutdown
boost::system::error_code ec;
socket_.shutdown(tcp::socket::shutdown_send, ec);
// At this point the connection is closed gracefully
}
};
//------------------------------------------------------------------------------
// Accepts incoming connections and launches the sessions
class listener : public std::enable_shared_from_this<listener> {
tcp::acceptor acceptor_;
tcp::socket socket_;
public:
listener(boost::asio::io_context &ioc, tcp::endpoint endpoint) : acceptor_(ioc), socket_(ioc) {
boost::system::error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if (ec) {
fail(ec, "open");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if (ec) {
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(boost::asio::socket_base::max_listen_connections, ec);
if (ec) {
fail(ec, "listen");
return;
}
}
// Start accepting incoming connections
void run() {
if (!acceptor_.is_open())
return;
do_accept();
}
void do_accept() {
acceptor_.async_accept(socket_, std::bind(&listener::on_accept, shared_from_this(), std::placeholders::_1));
}
void on_accept(boost::system::error_code ec) {
if (ec) {
fail(ec, "accept");
} else {
// Create the http_session and run it
std::make_shared<http_session>(std::move(socket_))->run();
}
// Accept another connection
do_accept();
}
};
//------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
// Check command line arguments.
if (argc != 4) {
std::cerr << "Usage: advanced-server <address> <port> <threads>\n"
<< "Example:\n"
<< " advanced-server 0.0.0.0 8080 1\n";
return EXIT_FAILURE;
}
auto const address = boost::asio::ip::make_address(argv[1]);
auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
auto const threads = std::max<int>(1, std::atoi(argv[3]));
// The io_context is required for all I/O
boost::asio::io_context ioc{ threads };
// Create and launch a listening port
std::make_shared<listener>(ioc, tcp::endpoint{ address, port })->run();
// Run the I/O service on the requested number of threads
std::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;
}
关于c++ - 我如何使 Boost Beast 从字符串而不是文件回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448622/
今天我在一个 Java 应用程序中看到了几种不同的加载文件的方法。 文件:/ 文件:// 文件:/// 这三个 URL 开头有什么区别?使用它们的首选方式是什么? 非常感谢 斯特凡 最佳答案 file
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the he
我有一个 javascript 文件,并且在该方法中有一个“测试”方法,我喜欢调用 C# 函数。 c# 函数与 javascript 文件不在同一文件中。 它位于 .cs 文件中。那么我该如何管理 j
需要检查我使用的文件/目录的权限 //filePath = path of file/directory access denied by user ( in windows ) File fil
我在一个目录中有很多 java 文件,我想在我的 Intellij 项目中使用它。但是我不想每次开始一个新项目时都将 java 文件复制到我的项目中。 我知道我可以在 Visual Studio 和
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a software
我有 3 个组件的 Twig 文件: 文件 1: {# content-here #} 文件 2: {{ title-here }} {# content-here #}
我得到了 mod_ldap.c 和 mod_authnz_ldap.c 文件。我需要使用 Linux 命令的 mod_ldap.so 和 mod_authnz_ldap.so 文件。 最佳答案 从 c
我想使用PIE在我的项目中使用 IE7。 但是我不明白的是,我只能在网络服务器上使用 .htc 文件吗? 我可以在没有网络服务器的情况下通过浏览器加载的本地页面中使用它吗? 我在 PIE 的文档中看到
我在 CI 管道中考虑这一点,我应该首先构建和测试我的应用程序,结果应该是一个 docker 镜像。 我想知道使用构建环境在构建服务器上构建然后运行测试是否更常见。也许为此使用构建脚本。最后只需将 j
using namespace std; struct WebSites { string siteName; int rank; string getSiteName() {
我是 Linux 新手,目前正在尝试使用 ginkgo USB-CAN 接口(interface) 的 API 编程功能。为了使用 C++ 对 API 进行编程,他们提供了库文件,其中包含三个带有 .
我刚学C语言,在实现一个程序时遇到了问题将 test.txt 文件作为程序的输入。 test.txt 文件的内容是: 1 30 30 40 50 60 2 40 30 50 60 60 3 30 20
如何连接两个tcpdump文件,使一个流量在文件中出现一个接一个?具体来说,我想“乘以”一个 tcpdump 文件,这样所有的 session 将一个接一个地按顺序重复几次。 最佳答案 mergeca
我有一个名为 input.MP4 的文件,它已损坏。它来自闭路电视摄像机。我什么都试过了,ffmpeg , VLC 转换,没有运气。但是,我使用了 mediainfo和 exiftool并提取以下信息
我想做什么? 我想提取 ISO 文件并编辑其中的文件,然后将其重新打包回 ISO 文件。 (正如你已经读过的) 我为什么要这样做? 我想开始修改 PSP ISO,为此我必须使用游戏资源、 Assets
给定一个 gzip 文件 Z,如果我将其解压缩为 Z',有什么办法可以重新压缩它以恢复完全相同的 gzip 文件 Z?在粗略阅读了 DEFLATE 格式后,我猜不会,因为任何给定的文件都可能在 DEF
我必须从数据库向我的邮件 ID 发送一封带有附件的邮件。 EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Adventure Works Admin
我有一个大的 M4B 文件和一个 CUE 文件。我想将其拆分为多个 M4B 文件,或将其拆分为多个 MP3 文件(以前首选)。 我想在命令行中执行此操作(OS X,但如果需要可以使用 Linux),而
快速提问。我有一个没有实现文件的类的项目。 然后在 AppDelegate 我有: #import "AppDelegate.h" #import "SomeClass.h" @interface A
我是一名优秀的程序员,十分优秀!