

新闻资讯
技术学院推荐使用 Boost.Asio 或 standalone asio 实现同步 HTTP 服务器,核心流程为监听端口→接受连接→读取请求→解析路径→构造并发送标准 HTTP 响应,代码简洁跨平台,避免底层 socket 复杂细节。
用C++实现一个简单的HTTP服务器,推荐直接使用 Boost.Asio(或其独立版本 asio,即 header-only 的 asio 库),它提供了跨平台、异步/同步、底层可控的网络编程能力,比手写 socket + select/poll/epoll 简洁得多,又比封装过重的框架(如 cpp-httplib)更贴近原理。
不追求高并发,先跑通“接收请求 → 解析 GET 路径 → 返回 HTML 响应”闭环。关键步骤:
GET /hello HTTP/1.1),提取路径使用 standalone asio(头文件版),无需编译 Boost:
#include #include#include #include #include using asio::ip::tcp;
std::stri
ng make_http_response(const std::string& path) { if (path == "/") { return "Hello, World!"; } else if (path == "/hello") { return "Hi there from C++ HTTP server!"; } else { return "404 Not Found"; } }
int main() { try { asio::io_context io; tcp::acceptor acceptor(io, tcp::endpoint(tcp::v4(), 8080)); std::cout << "HTTP server listening on https://www./link/c94b9c32bee1951814f79c9646777742";
while (true) { tcp::socket socket(io); acceptor.accept(socket); // 读请求(简化:最多读 1024 字节,找首个 \r\n\r\n) std::vectorbuf(1024); size_t len = socket.read_some(asio::buffer(buf)); std::string req(buf.begin(), buf.begin() + len); // 提取请求行中的路径(粗略解析) std::string path = "/"; size_t get_pos = req.find("GET "); if (get_pos != std::string::npos) { size_t start = get_pos + 4; size_t end = req.find(' ', start); if (end != std::string::npos && end > start) { path = req.substr(start, end - start); } } // 构造响应 std::string body = make_http_response(path); std::ostringstream resp; resp << "HTTP/1.1 200 OK\r\n" << "Content-Type: text/plain; charset=utf-8\r\n" << "Content-Length: " << body.size() << "\r\n" << "\r\n" << body; // 发送响应 asio::write(socket, asio::buffer(resp.str())); } } catch (std::exception& e) { std::cerr
编译命令(需 C++17,asio 已包含):
g++ -std=c++17 -I/path/to/asio/server.cpp -o httpd
访问 http://localhost:8080/hello 即可见响应。
这个例子是教学级,实际可用需补充:
http_parser 或自己写状态机,支持 POST、Header、Query 参数Content-Type,加 UTF-8 BOM 或 charset 声明std::filesystem 映射 /static/xxx.js 到磁盘路径,读文件发响应io_context::work + 多线程 run,避免单 acceptor 成瓶颈read_some/write 换成 async_read/async_write + handler,配合 io_context::run() 实现高并发Linux 下要处理 accept 返回 EAGAIN、read 返回 0(对端关闭)、TCP 粘包、缓冲区管理、超时控制、IPv6 兼容……这些 asio 都已封装好。你专注 HTTP 逻辑,不是系统调用细节。
基本上就这些。跑起来再逐步加功能,比一上来啃 epoll + 线程池 + 内存池轻松太多。