溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Rust中的smol使用實(shí)例分析

發(fā)布時間:2022-04-27 13:51:26 來源:億速云 閱讀:219 作者:iii 欄目:大數(shù)據(jù)

本文小編為大家詳細(xì)介紹“Rust中的smol使用實(shí)例分析”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Rust中的smol使用實(shí)例分析”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

簡介

smol  是一個輕量而高效的異步runtime。它采用了對標(biāo)準(zhǔn)庫進(jìn)行擴(kuò)展的方式,整個runtime只有大約1500行代碼。作者stjepang大神是大名鼎鼎crossbeam的作者。而他之前參與tokio和async-std的開發(fā)的經(jīng)驗(yàn)和思考,產(chǎn)生出了從頭開始構(gòu)建的smol這個庫。實(shí)際上在達(dá)到和tokio以及async-std相似的性能的前提下,smol代碼短線精悍,完全沒有依賴mio庫,API更加簡單,并且沒有unsafe代碼!而且,它還兼容tokio和async-std。讓我們看個簡單的例子

Tcp服務(wù)器端和客戶端

首先是一個echo服務(wù)器端
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(())    })}

兼容性

smol具有非常好的兼容性,比如說可以兼容tokio和async-std

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(())    })}

  • 注意,兼容tokio需要開啟以下feature
  
  [dependencies]smol = { version = "0.1", features = ["tokio02"] }

讀到這里,這篇“Rust中的smol使用實(shí)例分析”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(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)容。

AI