]> git.lizzy.rs Git - connect-rs.git/blobdiff - examples/tls-client/src/main.rs
refactor to have datagram already serialized in memory
[connect-rs.git] / examples / tls-client / src / main.rs
index cee675066c4d58c4c8e3d67906a48acdafc4fe7c..a73f4d5bb6448fcfaafb6358062088bdfc32d5a1 100644 (file)
@@ -1,6 +1,6 @@
-use connect::tls::rustls::ClientConfig;
 use connect::{ConnectDatagram, Connection, SinkExt, StreamExt};
 use log::*;
+use rustls::ClientConfig;
 use std::env;
 
 #[async_std::main]
@@ -11,15 +11,7 @@ async fn main() -> anyhow::Result<()> {
     let (ip_addr, domain, cafile_path) = parse_args();
 
     // construct `rustls` client config
-    let cafile = std::fs::read(cafile_path)?;
-
-    let mut client_pem = std::io::Cursor::new(cafile);
-
-    let mut client_config = ClientConfig::new();
-    client_config
-        .root_store
-        .add_pem_file(&mut client_pem)
-        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid cert"))?;
+    let client_config = create_client_config(cafile_path)?;
 
     // create a client connection to the server
     let mut conn = Connection::tls_client(ip_addr, &domain, client_config.into()).await?;
@@ -28,12 +20,12 @@ async fn main() -> anyhow::Result<()> {
     let msg = String::from("Hello world");
     info!("Sending message: {}", msg);
 
-    let envelope = ConnectDatagram::new(65535, msg.into_bytes())?;
+    let envelope = ConnectDatagram::with_tag(65535, msg.into_bytes())?;
     conn.writer().send(envelope).await?;
 
     // wait for the server to reply with an ack
-    if let Some(mut reply) = conn.reader().next().await {
-        let data = reply.take_data().unwrap();
+    if let Some(reply) = conn.reader().next().await {
+        let data = reply.data().to_vec();
         let msg = String::from_utf8(data)?;
 
         info!("Received message: {}", msg);
@@ -42,6 +34,20 @@ async fn main() -> anyhow::Result<()> {
     Ok(())
 }
 
+fn create_client_config(path: String) -> anyhow::Result<ClientConfig> {
+    let cafile = std::fs::read(path)?;
+
+    let mut client_pem = std::io::Cursor::new(cafile);
+
+    let mut client_config = ClientConfig::new();
+    client_config
+        .root_store
+        .add_pem_file(&mut client_pem)
+        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid cert"))?;
+
+    Ok(client_config)
+}
+
 fn parse_args() -> (String, String, String) {
     let args: Vec<String> = env::args().collect();