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.

492 lines
70 KiB

<!DOCTYPE HTML>
<html lang="zh-CN" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>I/O - Rust语言圣经(Rust Course)</title>
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<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>
<!-- Provide site root to javascript -->
<script type="text/javascript">
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 type="text/javascript">
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 type="text/javascript">
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('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.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="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></li></ol></li><li class="chapter-item "><a href="../basic/flow-control.html"><strong aria-hidden="true">2.5.</strong> 流程控制</a></li><li class="chapter-item "><a href="../basic/match-pattern/intro.html"><strong aria-hidden="true">2.6.</strong> 模式匹配</a><a class="toggle"><div></div></a></li><li>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<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 bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<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 (default)</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-practice/io.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 type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
// Get viewed page store
var viewed_key = 'mdbook-viewed';
var viewed_map = {};
try {
var viewed_storage = localStorage.getItem(viewed_key);
if (viewed_storage) {
viewed_map = JSON.parse(viewed_storage)
}
} catch (e) { }
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
// Apply viewed style
if (viewed_map[link.pathname]) {
link.classList.add('md-viewed')
}
});
// Mark viewed after 30s
setTimeout(function() {
viewed_map[location.pathname] = 1;
localStorage.setItem(viewed_key, JSON.stringify(viewed_map));
}, 30000)
</script>
<div id="content" class="content">
<!-- Page table of contents -->
<div class="sidetoc"><nav class="pagetoc"></nav></div>
<main>
<h1 id="io"><a class="header" href="#io">I/O</a></h1>
<p>本章节中我们将深入学习 Tokio 中的 I/O 操作,了解它的原理以及该如何使用。</p>
<p>Tokio 中的 I/O 操作和 <code>std</code> 在使用方式上几无区别,最大的区别就是前者是异步的,例如 Tokio 的读写特征分别是 <code>AsyncRead</code><code>AsyncWrite</code>:</p>
<ul>
<li>有部分类型按照自己的所需实现了它们: <code>TcpStream</code><code>File</code><code>Stdout</code></li>
<li>还有数据结构也实现了它们:<code>Vec&lt;u8&gt;</code><code>&amp;[u8]</code>,这样就可以直接使用这些数据结构作为读写器( reader / writer)</li>
</ul>
<h2 id="asyncread-和-asyncwrite"><a class="header" href="#asyncread-和-asyncwrite">AsyncRead 和 AsyncWrite</a></h2>
<p>这两个特征为字节流的异步读写提供了便利,通常我们会使用 <code>AsyncReadExt</code><code>AsyncWriteExt</code> 提供的工具方法,这些方法都使用 <code>async</code> 声明,且需要通过 <code>.await</code> 进行调用,</p>
<h4 id="async-fn-read"><a class="header" href="#async-fn-read">async fn read</a></h4>
<p><code>AsyncReadExt::read</code> 是一个异步方法可以将数据读入缓冲区( <code>buffer</code> )中,然后返回读取的字节数。</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::fs::File;
use tokio::io::{self, AsyncReadExt};
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let mut f = File::open(&quot;foo.txt&quot;).await?;
let mut buffer = [0; 10];
// 由于 buffer 的长度限制,当次的 `read` 调用最多可以从文件中读取 10 个字节的数据
let n = f.read(&amp;mut buffer[..]).await?;
println!(&quot;The bytes: {:?}&quot;, &amp;buffer[..n]);
Ok(())
}
</code></pre></pre>
<p>需要注意的是:当 <code>read</code> 返回 <code>Ok(0)</code> 时,意味着字节流( stream )已经关闭,在这之后继续调用 <code>read</code> 会立刻完成,依然获取到返回值 <code>Ok(0)</code>。 例如,字节流如果是 <code>TcpStream</code> 类型,那 <code>Ok(0)</code> 说明该<strong>连接的读取端已经被关闭</strong>(写入端关闭,会报其它的错误)。</p>
<h4 id="async-fn-read_to_end"><a class="header" href="#async-fn-read_to_end">async fn read_to_end</a></h4>
<p><code>AsyncReadExt::read_to_end</code> 方法会从字节流中读取所有的字节,直到遇到 <code>EOF</code> </p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::io::{self, AsyncReadExt};
use tokio::fs::File;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let mut f = File::open(&quot;foo.txt&quot;).await?;
let mut buffer = Vec::new();
// 读取整个文件的内容
f.read_to_end(&amp;mut buffer).await?;
Ok(())
}
</code></pre></pre>
<h4 id="async-fn-write"><a class="header" href="#async-fn-write">async fn write</a></h4>
<p><code>AsyncWriteExt::write</code> 异步方法会尝试将缓冲区的内容写入到写入器( <code>writer</code> )中,同时返回写入的字节数:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let mut file = File::create(&quot;foo.txt&quot;).await?;
let n = file.write(b&quot;some bytes&quot;).await?;
println!(&quot;Wrote the first {} bytes of 'some bytes'.&quot;, n);
Ok(())
}
</code></pre></pre>
<p>上面代码很清晰,但是大家可能会疑惑 <code>b&quot;some bytes&quot;</code> 是什么意思。这种写法可以将一个 <code>&amp;str</code> 字符串转变成一个字节数组:<code>&amp;[u8;10]</code>,然后 <code>write</code> 方法又会将这个 <code>&amp;[u8;10]</code> 的数组类型隐式强转为数组切片: <code>&amp;[u8]</code></p>
<h4 id="async-fn-write_all"><a class="header" href="#async-fn-write_all">async fn write_all</a></h4>
<p><code>AsyncWriteExt::write_all</code> 将缓冲区的内容全部写入到写入器中:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let mut file = File::create(&quot;foo.txt&quot;).await?;
file.write_all(b&quot;some bytes&quot;).await?;
Ok(())
}
</code></pre></pre>
<p>以上只是部分方法,实际上还有一些实用的方法由于篇幅有限无法列出,大家可以通过 <a href="https://docs.rs/tokio/latest/tokio/io/index.html">API 文档</a> 查看完整的列表。</p>
<h2 id="实用函数"><a class="header" href="#实用函数">实用函数</a></h2>
<p>另外,和标准库一样, <code>tokio::io</code> 模块包含了多个实用的函数或 API可以用于处理标准输入/输出/错误等。</p>
<p>例如,<code>tokio::io::copy</code> 异步的将读取器( <code>reader</code> )中的内容拷贝到写入器( <code>writer</code> )中。</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::fs::File;
use tokio::io;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let mut reader: &amp;[u8] = b&quot;hello&quot;;
let mut file = File::create(&quot;foo.txt&quot;).await?;
io::copy(&amp;mut reader, &amp;mut file).await?;
Ok(())
}
</code></pre></pre>
<p>还记得我们之前提到的字节数组 <code>&amp;[u8]</code> 实现了 <code>AsyncRead</code> 吗?正因为这个原因,所以这里可以直接将 <code>&amp;u8</code> 用作读取器。</p>
<h2 id="回声服务-echo-"><a class="header" href="#回声服务-echo-">回声服务( Echo )</a></h2>
<p>就如同写代码必写 <code>hello, world</code>,实现 web 服务器,往往会选择实现一个回声服务。该服务会将用户的输入内容直接返回给用户,就像回声壁一样。</p>
<p>具体来说,就是从用户建立的 TCP 连接的 socket 中读取到数据,然后立刻将同样的数据写回到该 socket 中。因此客户端会收到和自己发送的数据一模一样的回复。</p>
<p>下面我们将使用两种稍有不同的方法实现该回声服务。</p>
<h4 id="使用-iocopy"><a class="header" href="#使用-iocopy">使用 <code>io::copy()</code></a></h4>
<p>先来创建一个新的 bin 文件,用于运行我们的回声服务:</p>
<pre><code class="language-console">touch src/bin/echo-server-copy.rs
</code></pre>
<p>然后可以通过以下命令运行它(跟上一章节的方式相同)</p>
<pre><code class="language-console">cargo run --bin echo-server-copy
</code></pre>
<p>至于客户端,可以简单的使用 <code>telnet</code> 的方式来连接,或者也可以使用 <code>tokio::net::TcpStream</code>,它的<a href="https://docs.rs/tokio/1/tokio/net/struct.TcpStream.html#examples">文档示例</a>非常适合大家进行参考。</p>
<p>先来实现一下基本的服务器框架:通过 loop 循环接收 TCP 连接,然后为每一条连接创建一个单独的任务去处理。</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::io;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let listener = TcpListener::bind(&quot;127.0.0.1:6142&quot;).await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
// 在这里拷贝数据
});
}
}
</code></pre></pre>
<p>下面,来看看重头戏 <code>io::copy</code> ,它有两个参数:一个读取器,一个写入器,然后将读取器中的数据直接拷贝到写入器中,类似的实现代码如下:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>io::copy(&amp;mut socket, &amp;mut socket).await
<span class="boring">}
</span></code></pre></pre>
<p>这段代码相信大家一眼就能看出问题,由于我们的读取器和写入器都是同一个 socket因此需要对其进行两次可变借用这明显违背了 Rust 的借用规则。</p>
<h5 id="分离读写器"><a class="header" href="#分离读写器">分离读写器</a></h5>
<p>显然,使用同一个 socket 是不行的,为了实现目标功能,必须将 <code>socket</code> 分离成一个读取器和写入器。</p>
<p>任何一个读写器( reader + writer )都可以使用 <code>io::split</code> 方法进行分离,最终返回一个读取器和写入器,这两者可以独自的使用,例如可以放入不同的任务中。</p>
<p>例如,我们的回声客户端可以这样实现,以实现同时并发读写:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let socket = TcpStream::connect(&quot;127.0.0.1:6142&quot;).await?;
let (mut rd, mut wr) = io::split(socket);
// 创建异步任务,在后台写入数据
tokio::spawn(async move {
wr.write_all(b&quot;hello\r\n&quot;).await?;
wr.write_all(b&quot;world\r\n&quot;).await?;
// 有时,我们需要给予 Rust 一些类型暗示,它才能正确的推导出类型
Ok::&lt;_, io::Error&gt;(())
});
let mut buf = vec![0; 128];
loop {
let n = rd.read(&amp;mut buf).await?;
if n == 0 {
break;
}
println!(&quot;GOT {:?}&quot;, &amp;buf[..n]);
}
Ok(())
}
</code></pre></pre>
<p>实际上,<code>io::split</code> 可以用于任何同时实现了 <code>AsyncRead</code><code>AsyncWrite</code> 的值,它的内部使用了 <code>Arc</code><code>Mutex</code> 来实现相应的功能。如果大家觉得这种实现有些重,可以使用 Tokio 提供的 <code>TcpStream</code>,它提供了两种方式进行分离:</p>
<ul>
<li><a href="https://docs.rs/tokio/1.15.0/tokio/net/struct.TcpStream.html#method.split"><code>TcpStream::split</code></a>会获取字节流的引用,然后将其分离成一个读取器和写入器。但由于使用了引用的方式,它们俩必须和 <code>split</code> 在同一个任务中。 优点就是,这种实现没有性能开销,因为无需 <code>Arc</code><code>Mutex</code></li>
<li><a href="https://docs.rs/tokio/1.15.0/tokio/net/struct.TcpStream.html#method.into_split"><code>TcpStream::into_split</code></a>还提供了一种分离实现,分离出来的结果可以在任务间移动,内部是通过 <code>Arc</code> 实现</li>
</ul>
<p>再来分析下我们的使用场景,由于 <code>io::copy()</code> 调用时所在的任务和 <code>split</code> 所在的任务是同一个,因此可以使用性能最高的 <code>TcpStream::split</code>:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>tokio::spawn(async move {
let (mut rd, mut wr) = socket.split();
if io::copy(&amp;mut rd, &amp;mut wr).await.is_err() {
eprintln!(&quot;failed to copy&quot;);
}
});
<span class="boring">}
</span></code></pre></pre>
<p>使用 <code>io::copy</code> 实现的完整代码见<a href="https://github.com/tokio-rs/website/blob/master/tutorial-code/io/src/echo-server-copy.rs">此处</a></p>
<h4 id="手动拷贝"><a class="header" href="#手动拷贝">手动拷贝</a></h4>
<p>程序员往往拥有一颗手动干翻一切的心,因此如果你不想用 <code>io::copy</code> 来简单实现,还可以自己手动去拷贝数据:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -&gt; io::Result&lt;()&gt; {
let listener = TcpListener::bind(&quot;127.0.0.1:6142&quot;).await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = vec![0; 1024];
loop {
match socket.read(&amp;mut buf).await {
// 返回值 `Ok(0)` 说明对端已经关闭
Ok(0) =&gt; return,
Ok(n) =&gt; {
// Copy the data back to socket
// 将数据拷贝回 socket 中
if socket.write_all(&amp;buf[..n]).await.is_err() {
// 非预期错误,由于我们这里无需再做什么,因此直接停止处理
return;
}
}
Err(_) =&gt; {
// 非预期错误,由于我们无需再做什么,因此直接停止处理
return;
}
}
}
});
}
}
</code></pre></pre>
<p>建议这段代码放入一个和之前 <code>io::copy</code> 不同的文件中 <code>src/bin/echo-server.rs</code> 然后使用 <code>cargo run --bin echo-server</code> 运行。</p>
<p>下面一起来看看这段代码有哪些值得注意的地方。首先,由于使用了 <code>write_all</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 tokio::io::{self, AsyncReadExt, AsyncWriteExt};
<span class="boring">}
</span></code></pre></pre>
<h5 id="在堆上分配缓冲区"><a class="header" href="#在堆上分配缓冲区">在堆上分配缓冲区</a></h5>
<p>在上面代码中,我们需要将数据从 <code>socket</code> 中读取到一个缓冲区 <code>buffer</code> 中:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let mut buf = vec![0; 1024];
<span class="boring">}
</span></code></pre></pre>
<p>可以看到,此处的缓冲区是一个 <code>Vec</code> 动态数组,它的数据是存储在堆上,而不是栈上(若改成 <code>let mut buf = [0; 1024];</code>,则存储在栈上)。</p>
<p>在之前,我们提到过一个数据如果想在 <code>.await</code> 调用过程中存在,那它必须存储在当前任务内。在我们的代码中,<code>buf</code> 会在 <code>.await</code> 调用过程中被使用,因此它必须要存储在任务内。</p>
<p>若该缓冲区数组创建在栈上,那每条连接所对应的任务的内部数据结构看上去可能如下所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct Task {
task: enum {
AwaitingRead {
socket: TcpStream,
buf: [BufferType],
},
AwaitingWriteAll {
socket: TcpStream,
buf: [BufferType],
}
}
}
<span class="boring">}
</span></code></pre></pre>
<p>可以看到,栈数组要被使用,就必须存储在相应的结构体内,其中两个结构体分别持有了不同的栈数组 <code>[BufferType]</code>,这种方式会导致任务结构变得很大。特别地,我们选择缓冲区长度往往会使用分页长度(page size),因此使用栈数组会导致任务的内存大小变得很奇怪甚至糟糕:<code>$page-size + 一些额外的字节</code></p>
<p>当然,编译器会帮助我们做一些优化。例如,会进一步优化 <code>async</code> 语句块的布局,而不是像上面一样简单的使用 <code>enum</code>。在实践中,变量也不会在枚举成员间移动。</p>
<p>但是再怎么优化,任务的结构体至少也会跟其中的栈数组一样大,因此通常情况下,使用堆上的缓冲区会高效实用的多。</p>
<blockquote>
<p>当任务因为调度在线程间移动时,存储在栈上的数据需要进行保存和恢复,过大的栈上变量会带来不小的数据拷贝开销</p>
<p>因此,存储大量数据的变量最好放到堆上</p>
</blockquote>
<h5 id="处理-eof"><a class="header" href="#处理-eof">处理 EOF</a></h5>
<p>当 TCP 连接的读取端关闭后,再调用 <code>read</code> 方法会返回 <code>Ok(0)</code>。此时,再继续下去已经没有意义,因此我们需要退出循环。忘记在 EOF 时退出读取循环,是网络编程中一个常见的 bug :</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>loop {
match socket.read(&amp;mut buf).await {
Ok(0) =&gt; return,
// ... 其余错误处理
}
}
<span class="boring">}
</span></code></pre></pre>
<p>大家不妨深入思考下,如果没有退出循环会怎么样?之前我们提到过,一旦读取端关闭后,那后面的 <code>read</code> 调用就会立即返回 <code>Ok(0)</code>,而不会阻塞等待,因此这种无阻塞循环会最终导致 CPU 立刻跑到 100% ,并将一直持续下去,直到程序关闭。</p>
<div id="giscus-container"></div>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../advance-practice/channels.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" href="../advance-practice/frame.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-practice/channels.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" href="../advance-practice/frame.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 type="text/javascript">
window.playground_copyable = true;
</script>
<script src="../ace.js" type="text/javascript" charset="utf-8"></script>
<script src="../editor.js" type="text/javascript" charset="utf-8"></script>
<script src="../mode-rust.js" type="text/javascript" charset="utf-8"></script>
<script src="../theme-dawn.js" type="text/javascript" charset="utf-8"></script>
<script src="../theme-tomorrow_night.js" type="text/javascript" charset="utf-8"></script>
<script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="../book.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "advance-practice/io.md"
</script>
<!-- Custom JS scripts -->
<script type="text/javascript" src="../assets/custom.js"></script>
<script type="text/javascript" src="../assets/bigPicture.js"></script>
</body>
</html>