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实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too