摘要:本文从 TCP Socket 编程讲起,手写一个可运行的极简 HTTP 服务器,逐步实现请求解析、静态文件响应、线程池并发处理与优雅退出,并给出完整可编译的 C++ 代码与压测验证方法,帮助读者打通「网络编程 → 协议解析 → 并发模型」的完整链路。
一、为什么要手写一个 HTTP 服务器
调用框架很容易,但真正理解 HTTP 服务如何工作,往往需要自己动手写一遍。一个极简 HTTP 服务器虽然只有几百行代码,却完整覆盖了服务端开发的核心知识点:
- Socket 编程:socket、bind、listen、accept 的调用顺序与阻塞语义。
- 协议解析:HTTP 请求行、请求头、请求体的文本格式与边界处理。
- 响应构造:状态行、响应头、Content-Length 与连接关闭策略。
- 并发模型:多线程、线程池、连接队列与资源回收。
- 工程细节:信号处理、端口复用、错误码与日志。
本文目标是一个 Linux 下可直接编译运行的极简服务器,支持 GET 请求、静态文件返回、404 处理,并用线程池处理并发连接。
二、环境准备与项目结构
示例基于 Linux(或 WSL / macOS),使用 POSIX Socket API,编译器要求支持 C++17。
g++ --version # 建议 g++ 9 及以上
uname -a # Linux / macOS 均可
项目结构保持极简,单文件即可编译:
mini-http/
├── main.cpp # 服务器主逻辑
└── www/ # 静态资源目录
└── index.html
编译命令:
g++ -std=c++17 -O2 -pthread main.cpp -o mini_http
三、HTTP 协议最小知识
HTTP/1.1 是基于文本的请求-响应协议。一个典型的 GET 请求长这样:
GET /index.html HTTP/1.1
Host: 127.0.0.1:8080
User-Agent: curl/8.0
Accept: */*
服务器需要解析的关键信息:
- 请求行:方法、路径、协议版本,以空格分隔。
- 请求头:每行
Key: Value,以空行结束。 - 请求体:GET 通常没有;POST 由
Content-Length决定长度。
响应格式同样简单:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 13
Connection: close
Hello, World!
本文采用 Connection: close 的短连接策略,即每次请求处理完就关闭连接,逻辑最简单,也便于理解。后续可扩展为 keep-alive。
四、Socket 编程基础:服务端五步曲
TCP 服务端的标准流程可以概括为五步:
socket():创建监听套接字。bind():绑定 IP 与端口。listen():将套接字转为被动监听状态,维护连接队列。accept():从队列取出一个已完成三次握手的连接,返回新的通信套接字。read()/write():在通信套接字上收发数据,最后close()。
其中 SO_REUSEADDR 很关键:服务器重启时,处于 TIME_WAIT 状态的端口会导致 bind 失败,开启该选项可以立即复用端口。
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(8080);
bind(listen_fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
listen(listen_fd, SOMAXCONN);
注意 htonl / htons 的字节序转换:网络字节序是大端,主机字节序可能是小端,必须转换。
五、实现请求解析与响应构造
5.1 读取并解析请求
由于是短连接,可以循环 recv 直到读到 \r\n\r\n 或连接关闭。为简化处理,这里只解析请求行和请求头,忽略请求体。
struct HttpRequest {
std::string method;
std::string path;
std::string version;
std::unordered_map<std::string, std::string> headers;
};
bool parse_request(const std::string& raw, HttpRequest& req) {
std::istringstream stream(raw);
std::string line;
if (!std::getline(stream, line)) return false;
if (!line.empty() && line.back() == '\r') line.pop_back();
std::istringstream first(line);
if (!(first >> req.method >> req.path >> req.version)) return false;
while (std::getline(stream, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) break;
auto pos = line.find(':');
if (pos == std::string::npos) continue;
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
while (!value.empty() && value.front() == ' ') value.erase(value.begin());
req.headers[key] = value;
}
return true;
}
5.2 构造响应
响应需要根据文件是否存在返回 200 或 404,并正确设置 Content-Type 与 Content-Length。
std::string build_response(int status, const std::string& content_type,
const std::string& body) {
std::string status_text = (status == 200) ? "OK" : "Not Found";
std::ostringstream oss;
oss << "HTTP/1.1 " << status << " " << status_text << "\r\n"
<< "Content-Type: " << content_type << "\r\n"
<< "Content-Length: " << body.size() << "\r\n"
<< "Connection: close\r\n\r\n"
<< body;
return oss.str();
}
一个常见坑:Content-Length 必须是字节数,而不是字符数;读取文件时要用二进制模式,避免文本模式换行转换。
六、静态文件服务与路径安全
把 URL 路径映射到本地文件时,必须防止目录穿越攻击,例如 /../../etc/passwd。基本做法是规范化路径并校验前缀。
std::string resolve_path(const std::string& url_path) {
std::string path = url_path;
if (path == "/" || path.empty()) path = "/index.html";
// 拒绝包含 .. 的路径
if (path.find("..") != std::string::npos) return "";
std::string root = "./www";
std::string full = root + path;
char resolved[PATH_MAX];
if (realpath(full.c_str(), resolved) == nullptr) return "";
std::string real_root = realpath(root.c_str(), nullptr);
std::string real_file(resolved);
if (real_file.rfind(real_root, 0) != 0) return "";
return real_file;
}
根据扩展名返回 MIME 类型:
std::string mime_type(const std::string& path) {
auto ends_with = [&](const std::string& suffix) {
return path.size() >= suffix.size() &&
path.compare(path.size() - suffix.size(), suffix.size(), suffix) == 0;
};
if (ends_with(".html")) return "text/html; charset=utf-8";
if (ends_with(".css")) return "text/css; charset=utf-8";
if (ends_with(".js")) return "application/javascript";
if (ends_with(".png")) return "image/png";
if (ends_with(".jpg")) return "image/jpeg";
return "application/octet-stream";
}
七、并发处理:从多线程到线程池
7.1 朴素多线程的问题
最直接的做法是每 accept 一个连接就 std::thread 起一个线程。连接数一多,线程创建销毁开销和栈内存占用会迅速膨胀,甚至耗尽系统资源。
7.2 线程池设计
线程池的核心是「任务队列 + 固定工作线程」:主线程只负责 accept 并把连接 fd 投递到队列,工作线程循环取任务处理。
class ThreadPool {
public:
explicit ThreadPool(size_t n) {
for (size_t i = 0; i < n; ++i) {
workers_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock, [this] { return stop_ || !tasks_.empty(); });
if (stop_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
void submit(std::function<void()> task) {
{
std::lock_guard<std::mutex> lock(mtx_);
tasks_.push(std::move(task));
}
cv_.notify_one();
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lock(mtx_);
stop_ = true;
}
cv_.notify_all();
for (auto& t : workers_) t.join();
}
private:
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex mtx_;
std::condition_variable cv_;
bool stop_ = false;
};
注意析构顺序:先置 stop_ 并唤醒所有线程,再 join,避免线程卡在 wait 上导致程序无法退出。
八、完整代码实现
把前面的片段组装起来,得到完整可运行的服务器:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <climits>
#include <csignal>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <mutex>
#include <queue>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <condition_variable>
// ---------- 线程池 ----------
class ThreadPool {
public:
explicit ThreadPool(size_t n) {
for (size_t i = 0; i < n; ++i) {
workers_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock, [this] { return stop_ || !tasks_.empty(); });
if (stop_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
void submit(std::function<void()> task) {
{
std::lock_guard<std::mutex> lock(mtx_);
tasks_.push(std::move(task));
}
cv_.notify_one();
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lock(mtx_);
stop_ = true;
}
cv_.notify_all();
for (auto& t : workers_) t.join();
}
private:
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex mtx_;
std::condition_variable cv_;
bool stop_ = false;
};
// ---------- 请求解析 ----------
struct HttpRequest {
std::string method, path, version;
std::unordered_map<std::string, std::string> headers;
};
bool parse_request(const std::string& raw, HttpRequest& req) {
std::istringstream stream(raw);
std::string line;
if (!std::getline(stream, line)) return false;
if (!line.empty() && line.back() == '\r') line.pop_back();
std::istringstream first(line);
if (!(first >> req.method >> req.path >> req.version)) return false;
while (std::getline(stream, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) break;
auto pos = line.find(':');
if (pos == std::string::npos) continue;
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
while (!value.empty() && value.front() == ' ') value.erase(value.begin());
req.headers[key] = value;
}
return true;
}
// ---------- 响应构造 ----------
std::string build_response(int status, const std::string& content_type,
const std::string& body) {
std::string status_text = (status == 200) ? "OK" : "Not Found";
std::ostringstream oss;
oss << "HTTP/1.1 " << status << " " << status_text << "\r\n"
<< "Content-Type: " << content_type << "\r\n"
<< "Content-Length: " << body.size() << "\r\n"
<< "Connection: close\r\n\r\n"
<< body;
return oss.str();
}
// ---------- 路径与 MIME ----------
std::string mime_type(const std::string& path) {
auto ends_with = [&](const std::string& suffix) {
return path.size() >= suffix.size() &&
path.compare(path.size() - suffix.size(), suffix.size(), suffix) == 0;
};
if (ends_with(".html")) return "text/html; charset=utf-8";
if (ends_with(".css")) return "text/css; charset=utf-8";
if (ends_with(".js")) return "application/javascript";
if (ends_with(".png")) return "image/png";
if (ends_with(".jpg")) return "image/jpeg";
return "application/octet-stream";
}
std::string resolve_path(const std::string& url_path) {
std::string path = url_path;
if (path == "/" || path.empty()) path = "/index.html";
if (path.find("..") != std::string::npos) return "";
std::string root = "./www";
std::string full = root + path;
char resolved[PATH_MAX];
if (realpath(full.c_str(), resolved) == nullptr) return "";
std::string real_root = realpath(root.c_str(), nullptr);
std::string real_file(resolved);
if (real_file.rfind(real_root, 0) != 0) return "";
return real_file;
}
// ---------- 连接处理 ----------
void handle_client(int fd) {
std::string raw;
char buf[4096];
while (raw.find("\r\n\r\n") == std::string::npos) {
ssize_t n = recv(fd, buf, sizeof(buf), 0);
if (n <= 0) break;
raw.append(buf, n);
if (raw.size() > 64 * 1024) break;
}
HttpRequest req;
std::string response;
if (!parse_request(raw, req)) {
response = build_response(400, "text/plain", "Bad Request");
} else if (req.method != "GET") {
response = build_response(405, "text/plain", "Method Not Allowed");
} else {
std::string file = resolve_path(req.path);
std::ifstream ifs(file, std::ios::binary);
if (file.empty() || !ifs) {
response = build_response(404, "text/plain", "Not Found");
} else {
std::string body((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
response = build_response(200, mime_type(file), body);
}
}
size_t sent = 0;
while (sent < response.size()) {
ssize_t n = send(fd, response.data() + sent, response.size() - sent, 0);
if (n <= 0) break;
sent += n;
}
close(fd);
}
// ---------- 主函数 ----------
int main() {
signal(SIGPIPE, SIG_IGN);
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) { perror("socket"); return 1; }
int opt = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(8080);
if (bind(listen_fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
perror("bind"); return 1;
}
if (listen(listen_fd, SOMAXCONN) < 0) { perror("listen"); return 1; }
ThreadPool pool(4);
std::cout << "Listening on http://127.0.0.1:8080" << std::endl;
while (true) {
sockaddr_in client{};
socklen_t len = sizeof(client);
int fd = accept(listen_fd, reinterpret_cast<sockaddr*>(&client), &len);
if (fd < 0) {
if (errno == EINTR) continue;
perror("accept");
break;
}
pool.submit([fd] { handle_client(fd); });
}
close(listen_fd);
return 0;
}
几个容易忽略的细节:
signal(SIGPIPE, SIG_IGN):对端提前关闭连接时,send会触发 SIGPIPE 导致进程退出,必须忽略。send可能只发送部分数据,必须循环发送直到全部写完。accept可能被信号中断返回EINTR,应继续循环而不是退出。
九、编译运行与压测验证
准备一个测试页面:
mkdir -p www
echo '<h1>Hello from mini HTTP server</h1>' > www/index.html
g++ -std=c++17 -O2 -pthread main.cpp -o mini_http
./mini_http
另开终端验证:
curl -i http://127.0.0.1:8080/
curl -i http://127.0.0.1:8080/not-exist.html
curl -i http://127.0.0.1:8080/../../etc/passwd
预期结果:首页返回 200 与 HTML 内容;不存在的文件返回 404;目录穿越请求被拒绝。并发压测可用 ab 或 wrk:
ab -n 10000 -c 100 http://127.0.0.1:8080/
观察 QPS 与失败请求数,可以直观感受线程池大小对吞吐的影响。
十、性能与健壮性优化方向
| 方向 | 做法 | 收益 |
|---|---|---|
| IO 模型 | 用 epoll 替代阻塞 accept + 线程池 | 单机支撑更高并发连接 |
| 连接复用 | 支持 HTTP/1.1 keep-alive | 减少握手与线程切换开销 |
| 零拷贝 | sendfile 发送静态文件 | 减少用户态与内核态拷贝 |
| 请求体 | 解析 Content-Length 与 chunked | 支持 POST 等场景 |
| 日志与监控 | 结构化访问日志、耗时统计 | 便于定位慢请求 |
| 优雅退出 | 捕获 SIGINT,停止 accept 并等待任务完成 | 避免请求被硬中断 |
其中 epoll 是进阶重点:把监听 fd 与连接 fd 都注册到 epoll,事件循环中处理可读可写事件,配合非阻塞 IO 即可实现单线程高并发。这也是 Nginx、Redis 等高性能服务的核心思路。
十一、总结
本文从 Socket 五步曲出发,实现了一个支持静态文件、路径安全校验与线程池并发的极简 HTTP 服务器。核心结论可以归纳为三点:
- 协议很简单,边界很关键:请求头结束标记、Content-Length、部分发送等问题决定了服务是否稳定。
- 并发模型决定上限:线程池解决了线程爆炸问题,而 epoll 才能进一步突破连接数瓶颈。
- 安全不能省:路径穿越、SIGPIPE、端口复用这些细节,往往就是线上事故的来源。
建议读者在此基础上继续实现 keep-alive 与 epoll 版本,对比两者的压测数据,会对高性能网络编程有更直观的理解。
580



被折叠的 条评论
为什么被折叠?



