您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“Rust中的smol使用實(shí)例分析”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Rust中的smol使用實(shí)例分析”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
簡介
use std::net::{TcpListener, TcpStream};
use futures::io;
use smol::{Async, Task};
/// 原封不動返回輸入流
async fn echo(stream: Async<TcpStream>) -> io::Result<()> {
io::copy(&stream, &mut &stream).await?;
Ok(())
}
fn main() -> io::Result<()> {
smol::run(async {
// 創(chuàng)建listener
let listener = Async::<TcpListener>::bind("127.0.0.1:7000")?;
println!("Listening on {}", listener.get_ref().local_addr()?);
println!("Now start a TCP client.");
// 接受客戶端請求
loop {
let (stream, peer_addr) = listener.accept().await?;
println!("Accepted client: {}", peer_addr);
// 起一個task回應(yīng)客戶端
Task::spawn(echo(stream)).unwrap().detach();
}
})
}
然后是一個客戶端
use std::net::TcpStream;
use futures::io;
use futures::prelude::*;
use smol::Async;
fn main() -> io::Result<()> {
smol::run(async {
// 包裝出異步的標(biāo)準(zhǔn)輸入/輸出
let stdin = smol::reader(std::io::stdin());
let mut stdout = smol::writer(std::io::stdout());
// 連接服務(wù)器端
let stream = Async::<TcpStream>::connect("127.0.0.1:7000").await?;
println!("Connected to {}", stream.get_ref().peer_addr()?);
println!("Type a message and hit enter!\n");
// stdin -> 服務(wù)器;服務(wù)器返回 -> stdout
future::try_join(
io::copy(stdin, &mut &stream),
io::copy(&stream, &mut stdout),
)
.await?;
Ok(())
})
}
use std::time::{Duration, Instant};
use anyhow::{Error, Result};
fn main() -> Result<()> {
smol::run(async {
// 使用async-std的sleep
let start = Instant::now();
println!("Sleeping using async-std...");
async_std::task::sleep(Duration::from_secs(1)).await;
println!("Woke up after {:?}", start.elapsed());
// 使用tokio的sleep
let start = Instant::now();
println!("Sleeping using tokio...");
tokio::time::delay_for(Duration::from_secs(1)).await;
println!("Woke up after {:?}", start.elapsed());
Ok(())
})
}
[dependencies]smol = { version = "0.1", features = ["tokio02"] }
讀到這里,這篇“Rust中的smol使用實(shí)例分析”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。