Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

最后一个项目:构建多线程 Web 服务器

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 服务器的计划:

Here is our plan for building the web server:

  1. 了解一些关于 TCP 和 HTTP 的知识。

  2. 在套接字上监听 TCP 连接。

  3. 解析少量的 HTTP 请求。

  4. 创建一个正式的 HTTP 响应。

  5. 使用线程池提高服务器的吞吐量。

  6. Learn a bit about TCP and HTTP.

  7. Listen for TCP connections on a socket.

  8. Parse a small number of HTTP requests.

  9. Create a proper HTTP response.

  10. Improve the throughput of our server with a thread pool.

Screenshot of a web browser visiting the address 127.0.0.1:8080 displaying a webpage with the text content “Hello! Hi from Rust”

图 21-1:我们最后的共同项目

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.

在开始之前,我们应该提到两个细节。首先,我们将使用的方法并不是用 Rust 构建 Web 服务器的最佳方式。社区成员在 crates.io 上发布了许多生产级 crate,它们提供了比我们将构建的更完整的 Web 服务器和线程池实现。然而,我们在本章的意图是帮助你学习,而不是走捷径。因为 Rust 是一门系统编程语言,我们可以选择想要工作的抽象层级,并且可以深入到其他语言中不可能或不实际的底层。

其次,我们在这里不会使用 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.