smol/examples/tls-client.rs

49 lines
1.4 KiB
Rust
Raw Normal View History

2020-04-26 17:37:29 +00:00
//! A TCP client secured by TLS based on `async-native-tls`.
//!
//! First start a server:
//!
//! ```
//! cargo run --example tls-server
//! ```
//!
//! Then start a client:
//!
//! ```
//! cargo run --example tls-client
//! ```
2020-07-15 09:37:50 +00:00
use std::net::TcpStream;
2020-04-05 11:50:09 +00:00
use anyhow::Result;
2020-04-06 20:19:54 +00:00
use async_native_tls::{Certificate, TlsConnector};
2020-07-23 10:24:16 +00:00
use smol::{future, io, Async, Unblock};
2020-04-05 11:50:09 +00:00
fn main() -> Result<()> {
2020-04-26 17:37:29 +00:00
// Initialize TLS with the local certificate.
2020-04-05 11:50:09 +00:00
let mut builder = native_tls::TlsConnector::builder();
builder.add_root_certificate(Certificate::from_pem(include_bytes!("certificate.pem"))?);
2020-04-06 20:19:54 +00:00
let tls = TlsConnector::from(builder);
2020-04-05 11:50:09 +00:00
2020-08-26 21:59:49 +00:00
smol::block_on(async {
2020-04-26 17:37:29 +00:00
// Create async stdin and stdout handles.
2020-07-14 19:19:01 +00:00
let stdin = Unblock::new(std::io::stdin());
let mut stdout = Unblock::new(std::io::stdout());
2020-04-05 11:50:09 +00:00
2020-04-26 17:37:29 +00:00
// Connect to the server.
2020-07-15 09:37:50 +00:00
let stream = Async::<TcpStream>::connect(([127, 0, 0, 1], 7001)).await?;
2020-04-07 16:52:12 +00:00
let stream = tls.connect("127.0.0.1", stream).await?;
2020-07-15 09:37:50 +00:00
println!("Connected to {}", stream.get_ref().get_ref().peer_addr()?);
2020-04-26 17:37:29 +00:00
println!("Type a message and hit enter!\n");
2020-04-05 11:50:09 +00:00
2020-04-26 17:37:29 +00:00
// Pipe messages from stdin to the server and pipe messages from the server to stdout.
2020-07-14 19:19:01 +00:00
let stream = async_dup::Mutex::new(stream);
2020-08-26 21:59:49 +00:00
future::try_zip(
2020-04-05 11:50:09 +00:00
io::copy(stdin, &mut &stream),
io::copy(&stream, &mut stdout),
)
.await?;
Ok(())
})
}