推荐使用 Boost.Asio 或 standalone asio 实现同步 HTTP 服务器,核心流程为监听端口→接受连接→读取请求→解析路径→构造并发送标准 HTTP 响应,代码简洁跨平台,避免底层 socket 复杂细节。

用C++实现一个简单的HTTP服务器,推荐直接使用 Boost.Asio(或其独立版本 asio,即 header-only 的 asio 库),它提供了跨平台、异步/同步、底层可控的网络编程能力,比手写 socket + select/poll/epoll 简洁得多,又比封装过重的框架(如 cpp-httplib)更贴近原理。
核心思路:同步阻塞式 HTTP 服务器(适合理解+快速验证)
不追求高并发,先跑通“接收请求 → 解析 GET 路径 → 返回 HTML 响应”闭环。关键步骤:
- 创建 TCP acceptor,监听指定端口(如 8080)
- accept 客户端连接,得到 socket
- 读取 HTTP 请求(按行或按字节读,直到遇到空行)
- 简单解析请求行(如
GET /hello HTTP/1.1),提取路径 - 构造标准 HTTP 响应(状态行 + 头部 + 空行 + body)
- 写回 socket,关闭连接(HTTP/1.0 默认短连接)
最小可运行代码(仅依赖 asio,无 Boost)
使用 standalone asio(头文件版),无需编译 Boost:
#include <asio.hpp>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
<p>using asio::ip::tcp;</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><p>std::string 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";
}
}</p><p>int main() {
try {
asio::io_context io;
tcp::acceptor acceptor(io, tcp::endpoint(tcp::v4(), 8080));
std::cout << "HTTP server listening on <a href="https://www.php.cn/link/c94b9c32bee1951814f79c9646777742">https://www.php.cn/link/c94b9c32bee1951814f79c9646777742</a>";</p><pre class="brush:php;toolbar:false;">while (true) {
tcp::socket socket(io);
acceptor.accept(socket);
// 读请求(简化:最多读 1024 字节,找首个 \r\n\r\n)
std::vector<char> buf(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 已包含):
标签: linux html js json ipv6 字节 端口 ai c++ ios stream 网络编程 为什么
还木有评论哦,快来抢沙发吧~