boost库http服务器

boost库http服务器

基于boost标准C++库,使用协程和beast实现http服务器,仅添加支持post和get方法。

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/config.hpp>
#include <iostream>
#include <cstdlib>
#include <memory>
#include <string>
#include <thread>
#include <map>

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>
using namespace std;

typedef std::string (*pgetfunc)(void);
typedef std::string (*ppostfunc)(const std::string);
/******************************************* get ************************************************/
std::string print_cc(void)
{
	std::cout << "======== c c ========" << std::endl;
	return std::string("print_cc");
}

std::string print_dd(void)
{
	std::cout << "======== d d ========" << std::endl;
	return std::string("print_dd");
}


std::map<std::string, pgetfunc> get_supported = {
	{"/aa/bb/cc", print_cc},
	{"/aa/bb/dd", print_dd},
};

/******************************************** post *********************************************/
std::string print_ee(std::string strJson)
{
	std::cout << "======== e e ========" << strJson << std::endl;
	return std::string("print_cc");
}

std::string print_ff(std::string strJson)
{
	std::cout << "======== f f ========" << strJson << std::endl;
	return std::string("print_dd");
}


std::map<std::string, ppostfunc> post_supported = {
	{"/aa/bb/ee", print_ee},
	{"/aa/bb/ff", print_ff},
};


//------------------------------------------------------------------------------
auto select_protocol = [](beast::string_view offered_tokens) -> std::string
{
    // tokenize the Sec-Websocket-Protocol header offered by the client
    http::token_list offered( offered_tokens );

    // an array of protocols supported by this server
    // in descending order of preference
    static const std::array<beast::string_view, 4>
        supported = {
        "/aa/bb/cc",
        "/aa/bb/dd",
        "/aa/bb/ee",
		"/aa/bb/ff"
    };

    std::string result;
	auto iter = std::find(std::begin(supported), std::end(supported), offered_tokens);
	if (iter != std::end(supported)){
		result.assign(offered_tokens.begin(), offered_tokens.end());
	}

    return result;
};

// 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";
}

// 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)
{
    // 返回正常请求响应
    auto const success_request =
    [&req](beast::string_view body)
    {
        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.keep_alive(req.keep_alive());
        res.body() = std::string(body);
        res.prepare_payload();
        return res;
    };
    // 返回错误请求响应
    auto 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;
    };

    // 返回为查找到请求响应
    auto const not_found =
    [&req](beast::string_view method, 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 '" + std::string(method) + "' resource '" + std::string(target) + "' was not found.";
        res.prepare_payload();
        return res;
    };

    auto 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;
    };
    // 确保我们能处理这个方法
    if(req.method() != http::verb::get && req.method() != http::verb::head && req.method() != http::verb::post)
        return send(bad_request("Unknown HTTP-method"));
    // 请求路径必须是绝对路径且不包含 "..".
    if( req.target().empty() || req.target()[0] != '/' ||
        req.target().find("..") != beast::string_view::npos)
        return send(bad_request("Illegal request-target"));
	/****************************************************************************************************************/
    // 响应HEAD请求
    if(req.method() == http::verb::head) {
		auto const size = 0;
        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));
    }
	/****************************************************************************************************************/
    // 响应GET请求
    if(req.method() == http::verb::get){
		std::string protocol = select_protocol(req.target());
		
		if(get_supported.count(protocol) >0 ) {
			std::string body = get_supported[protocol]();
			return send(success_request(body));
		} else {
			return send(not_found(req.method(), req.target()));
		}
	}
	/****************************************************************************************************************/
    // 响应POST请求
	if(req.method()== http::verb::post){
		std::string protocol = select_protocol(req.target());
		
		if(post_supported.count(protocol) >0 ){
			std::string body = post_supported[protocol](req.body());
			return send(success_request(body));
		} else {
			return send(not_found(req.method(), req.target()));
		}
	}
}

//------------------------------------------------------------------------------

// Report a failure
void http_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.
template<class Stream>
struct send_lambda
{
    Stream& stream_;
    bool& close_;
    beast::error_code& ec_;

    explicit
    send_lambda(
        Stream& stream,
        bool& close,
        beast::error_code& ec)
        : stream_(stream)
        , close_(close)
        , ec_(ec)
    {
    }

    template<bool isRequest, class Body, class Fields>
    void
    operator()(http::message<isRequest, Body, Fields>&& msg) const
    {
        // Determine if we should close the connection after
        close_ = 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::write(stream_, sr, 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 reads
    beast::flat_buffer buffer;

    // This lambda is used to send messages
    send_lambda lambda{stream, close, ec, yield};

    for(;;)
    {
        // Set the timeout.
        stream.expires_after(std::chrono::seconds(30));

        // Read a request
        http::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 response
        handle_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 shutdown
    stream.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 acceptor
    tcp::acceptor acceptor(ioc);
    acceptor.open(endpoint.protocol(), ec);
    if(ec)
        return fail(ec, "open");

    // Allow address reuse
    acceptor.set_option(net::socket_base::reuse_address(true), ec);
    if(ec)
        return fail(ec, "set_option");

    // Bind to the server address
    acceptor.bind(endpoint, ec);
    if(ec)
        return fail(ec, "bind");

    // Start listening for connections
    acceptor.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");
        else
            boost::asio::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("192.168.31.111");
    auto const port = static_cast<unsigned short>(std::atoi("8066"));
    auto const doc_root = std::make_shared<std::string>("/");
    auto const threads = std::max<int>(1, std::atoi("2"));

    // The io_context is required for all I/O
    net::io_context ioc{threads};

    // Spawn a listening port
    boost::asio::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 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;
}

编译:

g++ -g -std=gnu++11 -o server http_server_coro.cpp -I/websocket/boost_1_73_0/  -L/websocket/boost_1_73_0/stage/lib  -lboost_context -lboost_coroutine -lboost_chrono -lpthread

 

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Boost是一个在C++标准之上提供可移植、跨平台的增强功能的开源Boost.httpBoost中的一个模块,它提供了HTTP协议的支持,使得C++程序能够更方便地实现HTTP通信。 Boost.http提供了一组类和函数,用于处理HTTP请求和响应。通过这些类和函数,我们可以方便地发送HTTP请求、接收HTTP响应,并处理请求和响应的各种属性,例如请求头、响应头、请求参数等。 在使用Boost.http实现HTTP功能时,我们首先需要创建一个HTTP客户端或服务器对象。客户端对象用于发送HTTP请求,而服务器对象用于接收和处理HTTP请求。 对于HTTP客户端,我们可以使用boost::beast::http::request类来构造HTTP请求并发送,例如构造一个GET请求发送到指定的URL地址。在发送请求后,我们可以通过读取boost::beast::http::response类来获取HTTP响应。 对于HTTP服务器,我们可以使用boost::beast::http::request_parser类来解析接收到的HTTP请求,然后根据请求的内容进行相应的处理。处理完毕后,可以使用boost::beast::http::response_creator类来构造HTTP响应并发送回客户端。 Boost.http还提供了其他一些有用的功能,例如重定向、处理cookie、处理SSL等。 通过使用Boost.http,我们可以更方便地实现基于HTTP协议的网络通信功能。而且,由于Boost的可移植性和跨平台性,我们的代码可以在不同的操作系统和编译器上运行,极大地增强了程序的可移植性和可扩展性。 ### 回答2: C++是一种强大的编程语言,而Boost则是C++语言中的一个重要工具。Boost提供了大量的功能和算法,可以帮助开发者更高效地进行C++编程。其中,Boost中的Boost.Asio模块提供了对HTTP/HTTPS和网络编程的支持。 在Boost中使用Boost.Asio模块实现HTTP/Web功能,需要以下步骤: 1. 引入Boost:首先,我们需要在自己的项目中引入Boost。可以通过下载Boost源代码并进行编译,或者直接使用已经编译好的二进制包。 2. 包含Asio头文件:在我们的代码中,需要包含Asio头文件,以便使用其中提供的HTTP/HTTPS和网络编程相关类和函数。 3. 创建HTTP请求和响应:使用Asio提供的类和函数,我们可以创建HTTP请求和响应对象,并设置相应的请求方法、URL、头部信息等。 4. 发送HTTP请求:通过Asio提供的socket对象,我们可以将HTTP请求发送到服务器,并等待服务器的响应。 5. 接收HTTP响应:当服务器返回响应时,我们可以使用Asio提供的相应函数,将响应内容保存到相应的数据结构中,以便我们进一步处理。 6. 处理响应:根据服务器返回的HTTP响应内容,我们可以进行相应的处理,如解析HTML、处理JSON数据等。 7. 关闭连接:当所有的请求和响应处理完成后,我们可以关闭与服务器的连接。 使用Boost的Asio模块,我们可以很方便地实现HTTP/Web功能,包括发送HTTP请求、接收和处理服务器的响应等。通过充分利用Boost的强大功能,我们可以编写高效、稳定的C++代码,实现各种应用程序中的网络功能。 ### 回答3: C++是一种高级编程语言,常用于开发高性能和跨平台的应用程序。Boost是一个开源的C++,提供了很多通用的功能组件和工具,用于增强C++程序的功能。而HTTP是一种基于客户端-服务器模型的协议,用于在Web上进行数据通信。 在C++中,我们可以使用Boost中的ASIO模块来实现基于HTTP的Web应用程序。ASIO(Asynchronous Input/Output)是一种基于事件驱动的异步I/O,能够实现高效的网络通信。 为了实现HTTP的功能,我们可以使用Boost中的HTTP模块。这个模块提供了HTTP的解析器和生成器,可以用于解析HTTP请求和构建HTTP响应。 使用Boost实现HTTP Web应用程序的一般步骤如下: 1. 导入Boost:在C++项目中,首先需要将Boost导入到项目中。可以从官方网站下载编译好的Boost,然后将其链接到项目中。 2. 创建HTTP服务器:使用Boost的ASIO模块创建一个HTTP服务器对象。这个服务器将监听指定的端口,接收和处理客户端的HTTP请求。 3. 处理HTTP请求:当服务器接收到客户端的HTTP请求时,使用Boost中的HTTP模块解析该请求,并提取请求的内容以及其他相关信息。根据请求的内容和参数,执行相应的操作。 4. 响应HTTP请求:根据处理结果,使用Boost中的HTTP模块生成HTTP响应,并将其发送给客户端。HTTP响应包括状态码、响应头和响应体等内容。 5. 清理资源:在服务器不再需要监听请求时,需要及时关闭服务器对象,并清理相关的资源。 总结起来,使用Boost的ASIO和HTTP模块,可以方便地实现基于HTTP的Web应用程序。通过解析HTTP请求和生成HTTP响应,我们可以实现各种功能,如网页服务、文件传输、数据交互等。 Boost提供了丰富的功能和工具,可以大大提高C++程序的开发效率和性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值