rust实现quic服务端和客户端

演示如何使用 Quinn 库实现一个简单的 QUIC 客户端和服务器。QUIC 是一种基于 UDP 的协议,用于在互联网上进行快速和安全的通信。

在程序中,使用了 Rust 的标准库中的 error、net 和 sync 模块,以及第三方库 tokio 和 quinn。程序使用了 async/await 语法来实现异步操作。

程序中的 run_server 函数使用了 accept_bi 函数来接受一个双向流,并使用 read 函数来接收数据。run_client 函数使用了 open_bi 函数来打开两个双向流,并使用 write_all 函数来发送数据。程序还使用了 set_priority 函数来设置流的优先级,以及 finish 函数来关闭流。

程序中还包括了一些辅助函数,如 make_server_endpoint 函数用于创建一个 QUIC 服务器端点,configure_client 函数用于配置客户端,configure_server 函数用于配置服务器,以及 SkipServerVerification 结构体用于跳过服务器证书验证。

这段代码演示了如何使用 Rust 和 Quinn 库实现一个简单的 QUIC 客户端和服务器,以及如何使用异步/等待语法来实现异步操作。

代码如下:

rust 复制代码
//! This example demonstrates how to make a QUIC connection that ignores the server certificate.
//!
//! Checkout the `README.md` for guidance.

use std::{error::Error, net::SocketAddr, sync::Arc};

use quinn::{ClientConfig, Endpoint, ServerConfig};
use tokio::io::AsyncWriteExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // server and client are running on the same thread asynchronously
    let addr = "127.0.0.1:5000".parse().unwrap();
    tokio::spawn(run_server(addr));
    run_client(addr).await?;
    Ok(())
}

/// Runs a QUIC server bound to given address.
async fn run_server(addr: SocketAddr) {
    let (endpoint, _server_cert) = make_server_endpoint(addr).unwrap();
    // accept a single connection
    let incoming_conn = endpoint.accept().await.unwrap();
    let conn = incoming_conn.await.unwrap();
    println!(
        "[server] connection accepted: addr={}",
        conn.remote_address()
    );
    loop {
        match conn.accept_bi().await {
            Ok((_send_stream, mut recv_stream)) => {
                println!("[server] stream accepted: {}", recv_stream.id());
                tokio::spawn(async move {
                    loop {
                        let mut buffer = vec![0u8; 1024 * 8];
                        match recv_stream.read(&mut buffer).await {
                            Ok(x) => match x {
                                Some(_) => {}
                                None => {
                                    println!("[server] stream closed");
                                    break;
                                }
                            },
                            Err(e) => {
                                println!("[server] read error: {}", e);
                                break;
                            }
                        }
                    }
                });
            }
            Err(e) => {
                println!("[server] connection error: {}", e);
                break;
            }
        }
    }
}

async fn run_client(server_addr: SocketAddr) -> Result<(), Box<dyn Error>> {
    let mut endpoint = Endpoint::client("127.0.0.1:0".parse().unwrap())?;
    endpoint.set_default_client_config(configure_client());

    // connect to server
    let connection = endpoint
        .connect(server_addr, "localhost")
        .unwrap()
        .await
        .unwrap();
    println!("[client] connected: addr={}", connection.remote_address());

    let (mut send_stream1, _recv_stream) = connection.open_bi().await?; // added mut keyword
    send_stream1.set_priority(0)?;
    let (mut send_stream2, _recv_stream) = connection.open_bi().await?;
    send_stream2.set_priority(2)?;
    send_stream1.write_all("buf1".as_bytes()).await.unwrap();
    send_stream2.write_all("buf2".as_bytes()).await.unwrap();

    send_stream1.finish().await.unwrap();
    if let Err(e) = send_stream2.finish().await {
        println!("[client] stream finish error: {}", e);
    }

    connection.close(0u32.into(), b"done");
    // Dropping handles allows the corresponding objects to automatically shut down
    //drop(connection);
    // Make sure the server has a chance to clean up
    endpoint.wait_idle().await;

    Ok(())
}

/// Dummy certificate verifier that treats any certificate as valid.
/// NOTE, such verification is vulnerable to MITM attacks, but convenient for testing.
struct SkipServerVerification;

impl SkipServerVerification {
    fn new() -> Arc<Self> {
        Arc::new(Self)
    }
}

impl rustls::client::ServerCertVerifier for SkipServerVerification {
    fn verify_server_cert(
        &self,
        _end_entity: &rustls::Certificate,
        _intermediates: &[rustls::Certificate],
        _server_name: &rustls::ServerName,
        _scts: &mut dyn Iterator<Item = &[u8]>,
        _ocsp_response: &[u8],
        _now: std::time::SystemTime,
    ) -> Result<rustls::client::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::ServerCertVerified::assertion())
    }
}

fn configure_client() -> ClientConfig {
    let crypto = rustls::ClientConfig::builder()
        .with_safe_defaults()
        .with_custom_certificate_verifier(SkipServerVerification::new())
        .with_no_client_auth();

    ClientConfig::new(Arc::new(crypto))
}

/// Constructs a QUIC endpoint configured to listen for incoming connections on a certain address
/// and port.
///
/// ## Returns
///
/// - a stream of incoming QUIC connections
/// - server certificate serialized into DER format
#[allow(unused)]
pub fn make_server_endpoint(bind_addr: SocketAddr) -> Result<(Endpoint, Vec<u8>), Box<dyn Error>> {
    let (server_config, server_cert) = configure_server()?;
    let endpoint = Endpoint::server(server_config, bind_addr)?;
    Ok((endpoint, server_cert))
}

/// Returns default server configuration along with its certificate.
fn configure_server() -> Result<(ServerConfig, Vec<u8>), Box<dyn Error>> {
    let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
    let cert_der = cert.serialize_der().unwrap();
    let priv_key = cert.serialize_private_key_der();
    let priv_key = rustls::PrivateKey(priv_key);
    let cert_chain = vec![rustls::Certificate(cert_der.clone())];

    let mut server_config = ServerConfig::with_single_cert(cert_chain, priv_key)?;
    let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();
    transport_config.max_concurrent_uni_streams(0_u8.into());

    Ok((server_config, cert_der))
}

#[allow(unused)]
pub const ALPN_QUIC_HTTP: &[&[u8]] = &[b"hq-29"];

Cargo.toml:

rust 复制代码
[package]
name = "quic_client"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
quinn = {version = "0.10.2"}
rustls = { version = "0.21.0" ,features = ["dangerous_configuration"]}
rcgen = "0.11.1"
tokio ={ version = "1.0.0",features = ["full"]}

运行结果:

相关推荐
一个小坑货5 小时前
Cargo Rust 的包管理器
开发语言·后端·rust
bluebonnet275 小时前
【Rust练习】22.HashMap
开发语言·后端·rust
VertexGeek7 小时前
Rust学习(八):异常处理和宏编程:
学习·算法·rust
前端与小赵1 天前
什么是Sass,有什么特点
前端·rust·sass
一个小坑货1 天前
Rust基础
开发语言·后端·rust
Object~1 天前
【第九课】Rust中泛型和特质
开发语言·后端·rust
码农飞飞1 天前
详解Rust结构体struct用法
开发语言·数据结构·后端·rust·成员函数·方法·结构体
Dontla2 天前
Rust derive macro(Rust #[derive])Rust派生宏
开发语言·后端·rust
fqbqrr2 天前
2411rust,编译时自动检查配置
rust
梦想画家2 天前
用Rust中byteorder包高效处理字节序列
rust·序列化·byteorder·文件编码