You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

528 lines
75 KiB

1 month ago
<!DOCTYPE HTML>
<html lang="zh-CN" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>实践应用Async Web 服务器 - Rust语言圣经(Rust Course)</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="../../favicon.svg">
<link rel="shortcut icon" href="../../favicon.png">
<link rel="stylesheet" href="../../css/variables.css">
<link rel="stylesheet" href="../../css/general.css">
<link rel="stylesheet" href="../../css/chrome.css">
<link rel="stylesheet" href="../../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../../highlight.css">
<link rel="stylesheet" href="../../tomorrow-night.css">
<link rel="stylesheet" href="../../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../../theme/style.css">
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "../../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
<div class="right-buttons">
<a href="../../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/sunface/rust-course/edit/main/src/advance/async/web-server.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<!-- Page table of contents -->
<div class="sidetoc"><nav class="pagetoc"></nav></div>
<main>
<h1 id="一个实践项目-web-服务器"><a class="header" href="#一个实践项目-web-服务器">一个实践项目: Web 服务器</a></h1>
<p>知识学得再多,不实际应用也是纸上谈兵,不是忘掉就是废掉,对于技术学习尤为如此。在之前章节中,我们已经学习了 <code>Async Rust</code> 的方方面面,现在来将这些知识融会贯通,最终实现一个并发 Web 服务器。</p>
<h2 id="多线程版本的-web-服务器"><a class="header" href="#多线程版本的-web-服务器">多线程版本的 Web 服务器</a></h2>
<p>在正式开始前,先来看一个单线程版本的 <code>Web</code> 服务器,该例子来源于 <a href="https://doc.rust-lang.org/book/ch20-01-single-threaded.html"><code>Rust Book</code></a> 一书。</p>
<p><code>src/main.rs</code>:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
fn main() {
// 监听本地端口 7878 ,等待 TCP 连接的建立
let listener = TcpListener::bind(&quot;127.0.0.1:7878&quot;).unwrap();
// 阻塞等待请求的进入
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
fn handle_connection(mut stream: TcpStream) {
// 从连接中顺序读取 1024 字节数据
let mut buffer = [0; 1024];
stream.read(&amp;mut buffer).unwrap();
let get = b&quot;GET / HTTP/1.1\r\n&quot;;
// 处理HTTP协议头若不符合则返回404和对应的 `html` 文件
let (status_line, filename) = if buffer.starts_with(get) {
(&quot;HTTP/1.1 200 OK\r\n\r\n&quot;, &quot;hello.html&quot;)
} else {
(&quot;HTTP/1.1 404 NOT FOUND\r\n\r\n&quot;, &quot;404.html&quot;)
};
let contents = fs::read_to_string(filename).unwrap();
// 将回复内容写入连接缓存中
let response = format!(&quot;{status_line}{contents}&quot;);
stream.write_all(response.as_bytes()).unwrap();
// 使用 flush 将缓存中的内容发送到客户端
stream.flush().unwrap();
}</code></pre></pre>
<p><code>hello.html</code>:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;title&gt;Hello!&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Hello!&lt;/h1&gt;
&lt;p&gt;Hi from Rust&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><code>404.html</code>:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;title&gt;Hello!&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Oops!&lt;/h1&gt;
&lt;p&gt;Sorry, I don't know what you're asking for.&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>运行以上代码,并从浏览器访问 <code>127.0.0.1:7878</code> 你将看到一条来自 <code>Ferris</code> 的问候。</p>
<p>在回忆了单线程版本该如何实现后,我们也将进入正题,一起来实现一个基于 <code>async</code> 的异步 Web 服务器。</p>
<h2 id="运行异步代码"><a class="header" href="#运行异步代码">运行异步代码</a></h2>
<p>一个 Web 服务器必须要能并发的处理大量来自用户的请求,也就是我们不能在处理完上一个用户的请求后,再处理下一个用户的请求。上面的单线程版本可以修改为多线程甚至于线程池来实现并发处理,但是线程还是太重了,使用 <code>async</code> 实现 <code>Web</code> 服务器才是最适合的。</p>
<p>首先将 <code>handle_connection</code> 修改为 <code>async</code> 实现:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>async fn handle_connection(mut stream: TcpStream) {
//&lt;-- snip --&gt;
}
<span class="boring">}</span></code></pre></pre>
<p>该修改会将函数的返回值从 <code>()</code> 变成 <code>Future&lt;Output=()&gt;</code> ,因此直接运行将不再有任何效果,只用通过 <code>.await</code> 或执行器的 <code>poll</code> 调用后才能获取 <code>Future</code> 的结果。</p>
<p>在之前的代码中,我们使用了自己实现的简单的执行器来进行 <code>.await</code><code>poll</code> ,实际上这只是为了学习原理,<strong>在实际项目中,需要选择一个三方的 <code>async</code> 运行时来实现相关的功能</strong>。 具体的选择我们将在下一章节进行讲解,现在先选择 <code>async-std</code> ,该包的最大优点就是跟标准库的 API 类似,相对来说更简单易用。</p>
<h4 id="使用-async-std-作为异步运行时"><a class="header" href="#使用-async-std-作为异步运行时">使用 <code>async-std</code> 作为异步运行时</a></h4>
<p>下面的例子将演示如何使用一个异步运行时 <code>async-std</code> 来让之前的 <code>async fn</code> 函数运行起来,该运行时允许使用属性 <code>#[async_std::main]</code> 将我们的 <code>fn main</code> 函数变成 <code>async fn main</code> ,这样就可以在 <code>main</code> 函数中直接调用其它 <code>async</code> 函数,否则你得用之前章节的 <code>block_on</code> 方法来让 <code>main</code> 去阻塞等待异步函数的完成,但是这种简单粗暴的阻塞等待方式并不灵活。</p>
<p>修改 <code>Cargo.toml</code> 添加 <code>async-std</code> 包并开启相应的属性:</p>
<pre><code class="language-toml">[dependencies]
futures = &quot;0.3&quot;
[dependencies.async-std]
version = &quot;1.6&quot;
features = [&quot;attributes&quot;]
</code></pre>
<p>下面将 <code>main</code> 函数修改为异步的,并在其中调用前面修改的异步版本 <code>handle_connection</code> :</p>
<pre><pre class="playground"><code class="language-rust edition2021">#[async_std::main]
async fn main() {
let listener = TcpListener::bind(&quot;127.0.0.1:7878&quot;).unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
// 警告,这里无法并发
handle_connection(stream).await;
}
}</code></pre></pre>
<p><strong>上面的代码虽然已经是异步的,实际上它还无法并发</strong>,原因我们后面会解释,先来模拟一下慢请求:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::time::Duration;
use async_std::task;
async fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&amp;mut buffer).unwrap();
let get = b&quot;GET / HTTP/1.1\r\n&quot;;
let sleep = b&quot;GET /sleep HTTP/1.1\r\n&quot;;
let (status_line, filename) = if buffer.starts_with(get) {
(&quot;HTTP/1.1 200 OK\r\n\r\n&quot;, &quot;hello.html&quot;)
} else if buffer.starts_with(sleep) {
task::sleep(Duration::from_secs(5)).await;
(&quot;HTTP/1.1 200 OK\r\n\r\n&quot;, &quot;hello.html&quot;)
} else {
(&quot;HTTP/1.1 404 NOT FOUND\r\n\r\n&quot;, &quot;404.html&quot;)
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!(&quot;{status_line}{contents}&quot;);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
<span class="boring">}</span></code></pre></pre>
<p>上面是全新实现的 <code>handle_connection</code> ,它会在内部睡眠 5 秒,模拟一次用户慢请求,需要注意的是,我们并没有使用 <code>std::thread::sleep</code> 进行睡眠,原因是该函数是阻塞的,它会让当前线程陷入睡眠中,导致其它任务无法继续运行!因此我们需要一个睡眠函数 <code>async_std::task::sleep</code>,它仅会让当前的任务陷入睡眠,然后该任务会让出线程的控制权,这样线程就可以继续运行其它任务。</p>
<p>因此,光把函数变成 <code>async</code> 往往是不够的,还需要将它内部的代码也都变成异步兼容的,阻塞线程绝对是不可行的。</p>
<p>现在运行服务器,并访问 <code>127.0.0.1:7878/sleep</code> 你会发现只有在完成第一个用户请求(5 秒后),才能开始处理第二个用户请求。现在再来看看该如何解决这个问题,让请求并发起来。</p>
<h2 id="并发地处理连接"><a class="header" href="#并发地处理连接">并发地处理连接</a></h2>
<p>上面代码最大的问题是 <code>listener.incoming()</code> 是阻塞的迭代器。当 <code>listener</code> 在等待连接时,执行器是无法执行其它 <code>Future</code> 的,而且只有在我们处理完已有的连接后,才能接收新的连接。</p>
<p>解决方法是将 <code>listener.incoming()</code> 从一个阻塞的迭代器变成一个非阻塞的 <code>Stream</code> 后者在前面章节有过专门介绍:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use async_std::net::TcpListener;
use async_std::net::TcpStream;
use futures::stream::StreamExt;
#[async_std::main]
async fn main() {
let listener = TcpListener::bind(&quot;127.0.0.1:7878&quot;).await.unwrap();
listener
.incoming()
.for_each_concurrent(/* limit */ None, |tcpstream| async move {
let tcpstream = tcpstream.unwrap();
handle_connection(tcpstream).await;
})
.await;
}</code></pre></pre>
<p>异步版本的 <code>TcpListener</code><code>listener.incoming()</code> 实现了 <code>Stream</code> 特征,以上修改有两个好处:</p>
<ul>
<li><code>listener.incoming()</code> 不再阻塞</li>
<li>使用 <code>for_each_concurrent</code> 并发地处理从 <code>Stream</code> 获取的元素</li>
</ul>
<p>现在上面的实现的关键在于 <code>handle_connection</code> 不能再阻塞:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use async_std::prelude::*;
async fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&amp;mut buffer).await.unwrap();
//&lt;-- snip --&gt;
stream.write(response.as_bytes()).await.unwrap();
stream.flush().await.unwrap();
}
<span class="boring">}</span></code></pre></pre>
<p>在将数据读写改造成异步后,现在该函数也彻底变成了异步的版本,因此一次慢请求不再会阻止其它请求的运行。</p>
<h2 id="使用多线程并行处理请求"><a class="header" href="#使用多线程并行处理请求">使用多线程并行处理请求</a></h2>
<p>聪明的读者不知道有没有发现,之前的例子有一个致命的缺陷:只能使用一个线程并发的处理用户请求。是的,这样也可以实现并发,一秒处理几千次请求问题不大,但是这毕竟没有利用上 CPU 的多核并行能力,无法实现性能最大化。</p>
<p><code>async</code> 并发和多线程其实并不冲突,而 <code>async-std</code> 包也允许我们使用多个线程去处理,由于 <code>handle_connection</code> 实现了 <code>Send</code> 特征且不会阻塞,因此使用 <code>async_std::task::spawn</code> 是非常安全的:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use async_std::task::spawn;
#[async_std::main]
async fn main() {
let listener = TcpListener::bind(&quot;127.0.0.1:7878&quot;).await.unwrap();
listener
.incoming()
.for_each_concurrent(/* limit */ None, |stream| async move {
let stream = stream.unwrap();
spawn(handle_connection(stream));
})
.await;
}</code></pre></pre>
<p>至此,我们实现了同时使用并行(多线程)和并发( <code>async</code> )来同时处理多个请求!</p>
<h2 id="测试-handle_connection-函数"><a class="header" href="#测试-handle_connection-函数">测试 <code>handle_connection</code> 函数</a></h2>
<p>对于测试 Web 服务器,使用集成测试往往是最简单的,但是在本例子中,将使用单元测试来测试连接处理函数的正确性。</p>
<p>为了保证单元测试的隔离性和确定性,我们使用 <code>MockTcpStream</code> 来替代 <code>TcpStream</code> 。首先,修改 <code>handle_connection</code> 的函数签名让测试更简单,之所以可以修改签名,原因在于 <code>async_std::net::TcpStream</code> 实际上并不是必须的,只要任何结构体实现了 <code>async_std::io::Read</code>, <code>async_std::io::Write</code><code>marker::Unpin</code> 就可以替代它:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::marker::Unpin;
use async_std::io::{Read, Write};
async fn handle_connection(mut stream: impl Read + Write + Unpin) {
<span class="boring">}</span></code></pre></pre>
<p>下面,来构建一个 mock 的 <code>TcpStream</code> 并实现了上面这些特征,它包含一些数据,这些数据将被拷贝到 <code>read</code> 缓存中, 然后返回 <code>Poll::Ready</code> 说明 <code>read</code> 已经结束:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use super::*;
use futures::io::Error;
use futures::task::{Context, Poll};
use std::cmp::min;
use std::pin::Pin;
struct MockTcpStream {
read_data: Vec&lt;u8&gt;,
write_data: Vec&lt;u8&gt;,
}
impl Read for MockTcpStream {
fn poll_read(
self: Pin&lt;&amp;mut Self&gt;,
_: &amp;mut Context,
buf: &amp;mut [u8],
) -&gt; Poll&lt;Result&lt;usize, Error&gt;&gt; {
let size: usize = min(self.read_data.len(), buf.len());
buf[..size].copy_from_slice(&amp;self.read_data[..size]);
Poll::Ready(Ok(size))
}
}
<span class="boring">}</span></code></pre></pre>
<p><code>Write</code>的实现也类似,需要实现三个方法 : <code>poll_write</code>, <code>poll_flush</code>, 与 <code>poll_close</code><code>poll_write</code> 会拷贝输入数据到 mock 的 <code>TcpStream</code> 中,当完成后返回 <code>Poll::Ready</code>。由于 <code>TcpStream</code> 无需 <code>flush</code><code>close</code>,因此另两个方法直接返回 <code>Poll::Ready</code> 即可。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl Write for MockTcpStream {
fn poll_write(
mut self: Pin&lt;&amp;mut Self&gt;,
_: &amp;mut Context,
buf: &amp;[u8],
) -&gt; Poll&lt;Result&lt;usize, Error&gt;&gt; {
self.write_data = Vec::from(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin&lt;&amp;mut Self&gt;, _: &amp;mut Context) -&gt; Poll&lt;Result&lt;(), Error&gt;&gt; {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin&lt;&amp;mut Self&gt;, _: &amp;mut Context) -&gt; Poll&lt;Result&lt;(), Error&gt;&gt; {
Poll::Ready(Ok(()))
}
}
<span class="boring">}</span></code></pre></pre>
<p>最后,我们的 mock 需要实现 <code>Unpin</code> 特征,表示它可以在内存中安全的移动,具体内容在<a href="https://course.rs/advance/async/pin-unpin.html">前面章节</a>有讲。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::marker::Unpin;
impl Unpin for MockTcpStream {}
<span class="boring">}</span></code></pre></pre>
<p>现在可以准备开始测试了,在使用初始化数据设置好 <code>MockTcpStream</code> 后,我们可以使用 <code>#[async_std::test]</code> 来运行 <code>handle_connection</code> 函数,该函数跟 <code>#[async_std::main]</code> 的作用类似。为了确保 <code>handle_connection</code> 函数正确工作,需要根据初始化数据检查正确的数据被写入到 <code>MockTcpStream</code> 中。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::fs;
#[async_std::test]
async fn test_handle_connection() {
let input_bytes = b&quot;GET / HTTP/1.1\r\n&quot;;
let mut contents = vec![0u8; 1024];
contents[..input_bytes.len()].clone_from_slice(input_bytes);
let mut stream = MockTcpStream {
read_data: contents,
write_data: Vec::new(),
};
handle_connection(&amp;mut stream).await;
let mut buf = [0u8; 1024];
stream.read(&amp;mut buf).await.unwrap();
let expected_contents = fs::read_to_string(&quot;hello.html&quot;).unwrap();
let expected_response = format!(&quot;HTTP/1.1 200 OK\r\n\r\n{}&quot;, expected_contents);
assert!(stream.write_data.starts_with(expected_response.as_bytes()));
}
<span class="boring">}</span></code></pre></pre>
<div id="giscus-container"></div>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../../advance/async/pain-points-and-workarounds.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../../advance-practice1/intro.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../../advance/async/pain-points-and-workarounds.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../../advance-practice1/intro.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="../../ace.js"></script>
<script src="../../editor.js"></script>
<script src="../../mode-rust.js"></script>
<script src="../../theme-dawn.js"></script>
<script src="../../theme-tomorrow_night.js"></script>
<script src="../../elasticlunr.min.js"></script>
<script src="../../mark.min.js"></script>
<script src="../../searcher.js"></script>
<script src="../../clipboard.min.js"></script>
<script src="../../highlight.js"></script>
<script src="../../book.js"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "advance/async/web-server.md"
</script>
<!-- Custom JS scripts -->
<script src="../../assets/custom.js"></script>
<script src="../../assets/bigPicture.js"></script>
</div>
</body>
</html>