c++ http client and server implementation

In C++, you can use third-party libraries or native libraries to implement HTTP clients and servers. Here are two common methods:

1. Use third party library:
   - For HTTP client, you can use third party library like curl or cpp-httplib. These libraries provide an easy-to-use interface to send HTTP requests and process responses.
   - For the HTTP server, you can use a third-party library like Boost.Beast, Crow, Pistache or cpp-httplib. These libraries help you create HTTP servers that process requests from clients and generate responses.

2. Using native libraries:
   - For HTTP client, you can use `libcurl` from the C++ standard library to send HTTP requests and process responses. `libcurl` is a powerful open source library that supports multiple protocols, including HTTP.
   - For the HTTP server, you can use the `boost::asio` library in the C++ standard library to create a TCP-based server, and then implement the processing logic of the HTTP protocol on the server. You need to parse HTTP requests, generate HTTP responses, and process HTTP headers and data.

The following is a basic code example for writing an HTTP client and server in C++:

HTTP client:

#include <iostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

int main() {
    boost::asio::io_context io_context;

    // 创建 socket 对象
    tcp::socket socket(io_context);

    // 解析服务器地址和端口
    tcp::resolver resolver(io_context);
    tcp::resolver::results_type endpoints = resolver.resolve("www.example.com", "http");

    // 连接服务器
    boost::asio::connect(socket, endpoints);

    // 构建 HTTP 请求
    std::string request = "GET / HTTP/1.1\r\n"
                          "Host: www.example.com\r\n"
                          "Connection: close\r\n\r\n";

    // 发送请求
    boost::asio::write(socket, boost::asio::buffer(request));

    // 读取并打印响应
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    std::ostream response_stream(&response);
    std::string status_line;
    std::getline(response_stream, status_line);
    std::cout << "Response: " << status_line << std::endl;

    // 读取并打印剩余响应内容
    if (response.size() > 0) {
        std::cout << &response;
    }

    return 0;
}

HTTP server:

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using boost::asio::ip::tcp;

void handle_request(const boost::system::error_code& error, std::size_t bytes_transferred) {
    if (!error) {
        // 构建 HTTP 响应
        std::string response = "HTTP/1.1 200 OK\r\n"
                               "Content-Length: 13\r\n"
                               "Content-Type: text/plain\r\n\r\n"
                               "Hello, World!";

        // 发送响应
        boost::asio::write(*socket, boost::asio::buffer(response));
    }
}

void start_accept(tcp::acceptor& acceptor) {
    tcp::socket socket(acceptor.get_executor().context());

    // 异步接受连接
    acceptor.async_accept(socket, [&](const boost::system::error_code& error) {
        if (!error) {
            // 异步处理请求
            boost::asio::async_write(socket, boost::asio::buffer("Hello, World!\n"), handle_request);
        }

        // 继续接受下一个连接
        start_accept(acceptor);
    });
}

int main() {
    boost::asio::io_context io_context;

    // 创建 acceptor 对象,监听指定端口
    tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 8080));

    // 开始接受连接
    start_accept(acceptor);

    // 运行 io_context
    io_context.run();

    return 0;
}

The code sample above uses the Boost.Asio library to handle network communication, where the HTTP client sends a GET request to www.example.com, and reads and prints the server's response. The HTTP server listens to the local port 8080, and sends a simple HTTP response after receiving the connection.

In order to compile and run the above code, you need to install the Boost library and link the Boost library with the appropriate compile options.

Guess you like

Origin blog.csdn.net/feng1790291543/article/details/132164997