4个版本
0.1.3 | 2022年4月27日 |
---|---|
0.1.2 | 2022年4月25日 |
0.1.1 | 2022年4月24日 |
0.1.0 | 2022年4月10日 |
#9 in #tokio-rustls
在 2 个crate中使用 (通过 multistream)
15KB
223 行
Easy Tokio Rustls
该库为使用 tokio-rustls
创建简单的TLS套接字提供了便捷的抽象。
客户端使用示例
use anyhow::Result;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use easy_tokio_rustls::TlsClient;
const BUFFER_SIZE: usize = 8 * 1024;
const REQUEST: &[u8] = b"GET / HTTP/1.1\r\nHost: suchprogramming.com\r\n\r\n";
#[tokio::main]
async fn main() -> Result<()> {
let client = TlsClient::new("suchprogramming.com:443").await?;
let mut connection = client.connect().await?;
connection.write_all(REQUEST).await?;
let mut buffer = [0; BUFFER_SIZE];
loop {
let read_size = connection.read(&mut buffer).await?;
if read_size == 0 {
connection.shutdown().await?;
return Ok(());
}
let html = std::str::from_utf8(&buffer[0..read_size]).unwrap();
print!("{}", html);
if html.contains("</html>") {
connection.shutdown().await?;
return Ok(());
}
}
}
服务器使用示例
use anyhow::Result;
use std::str;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use easy_tokio_rustls::TlsServer;
const BUFFER_SIZE: usize = 8 * 1024;
const RESPONSE: &[u8] = b"HTTP/1.1 200 OK\r\nServer: a very great server\r\n\r\n";
#[tokio::main]
pub async fn main() -> Result<()> {
let interface = "0.0.0.0:8443";
let cert_file = "cert.pem";
let key_file = "privkey.pem";
let server = TlsServer::new(interface, cert_file, key_file).await?;
let listener = server.listen().await?;
println!("Listening on {}", interface);
// This is a simplified server, handling 1 connection at a time certainly isn't recommended
let (stream, addr) = listener.stream_accept().await?;
println!("Client connected from {}", addr);
let mut client = stream.tls_accept().await?;
println!("TLS connection accepted");
let mut buffer = [0; BUFFER_SIZE];
let read_size = client.read(&mut buffer).await?;
let request = str::from_utf8(&buffer[..read_size])?;
println!("Client sent:\n{}", request);
client.write_all(RESPONSE).await?;
client.flush().await?;
println!("Reply sent, shutting down...");
client.shutdown().await?;
Ok(())
}
未来特性
我想添加到这个项目的功能
- mTLS认证
- 证书固定
依赖项
~13–24MB
~429K SLoC