rust实现quic服务端和客户端

2023-11-11 07:01

本文主要是介绍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 客户端和服务器,以及如何使用异步/等待语法来实现异步操作。

代码如下:

//! 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 asynchronouslylet 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 connectionlet 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 serverlet 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 keywordsend_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 upendpoint.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:

[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"]}

运行结果:

这篇关于rust实现quic服务端和客户端的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/388340

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal