x-i18n: generated_at: “2026-03-01T15:03:42Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 2a0e9ef98893b80390e0c428b109ad90bc200852c6bc0151144bcdf6843f2abd source_path: ch21-00-final-project-a-web-server.md workflow: 16
最终项目:构建一个多线程 Web 服务器 (Final Project: Building a Multithreaded Web Server)
Final Project: Building a Multithreaded Web Server
这是一段漫长的旅程,但我们已经到达了本书的尽头。在本章中,我们将一起再构建一个项目,以演示我们在最后几章中涵盖的一些概念,并回顾一些早期的课程。
It’s been a long journey, but we’ve reached the end of the book. In this chapter, we’ll build one more project together to demonstrate some of the concepts we covered in the final chapters, as well as recap some earlier lessons.
作为我们的最终项目,我们将制作一个会说 “Hello!” 的 Web 服务器,在 Web 浏览器中看起来如图 21-1 所示。
For our final project, we’ll make a web server that says “Hello!” and looks like Figure 21-1 in a web browser.
以下是我们构建 Web 服务器的计划:
- 了解一些关于 TCP 和 HTTP 的知识。
- 在套接字 (socket) 上监听 TCP 连接。
- 解析少量的 HTTP 请求。
- 创建一个正式的 HTTP 响应。
- 使用线程池提高服务器的吞吐量。
Here is our plan for building the web server:
- Learn a bit about TCP and HTTP.
- Listen for TCP connections on a socket.
- Parse a small number of HTTP requests.
- Create a proper HTTP response.
- Improve the throughput of our server with a thread pool.
图 21-1:我们最后的共享项目
在我们开始之前,我们应该提到两个细节。首先,我们将使用的方法并不是用 Rust 构建 Web 服务器的最佳方式。社区成员已经在 crates.io 上发布了许多生产级的 crate,它们提供了比我们将要构建的更完整的 Web 服务器和线程池实现。然而,我们在本章的意图是帮助你学习,而不是走捷径。因为 Rust 是一门系统编程语言,我们可以选择想要使用的抽象级别,并且可以深入到比其他语言中可能或实际可行的更低级别。
Before we get started, we should mention two details. First, the method we’ll use won’t be the best way to build a web server with Rust. Community members have published a number of production-ready crates available at crates.io that provide more complete web server and thread pool implementations than we’ll build. However, our intention in this chapter is to help you learn, not to take the easy route. Because Rust is a systems programming language, we can choose the level of abstraction we want to work with and can go to a lower level than is possible or practical in other languages.
其次,我们在这里不会使用 async 和 await。构建线程池本身就是一个足够大的挑战,不需要再加上构建一个异步运行时!然而,我们会注意到 async 和 await 可能适用于我们在本章中将看到的一些相同问题。归根结底,正如我们在第 17 章中指出的,许多异步运行时都使用线程池来管理它们的工作。
Second, we will not be using async and await here. Building a thread pool is a big enough challenge on its own, without adding in building an async runtime! However, we will note how async and await might be applicable to some of the same problems we will see in this chapter. Ultimately, as we noted back in Chapter 17, many async runtimes use thread pools for managing their work.
因此,我们将手动编写基础的 HTTP 服务器和线程池,以便你可以了解你将来可能使用的 crate 背后的通用思想和技术。
We’ll therefore write the basic HTTP server and thread pool manually so that you can learn the general ideas and techniques behind the crates you might use in the future.