]> git.lizzy.rs Git - connect-rs.git/blob - examples/tls-client/src/main.rs
rename stitch-net to connect
[connect-rs.git] / examples / tls-client / src / main.rs
1 use log::*;
2 use seam_channel::net::tls::rustls::ClientConfig;
3 use seam_channel::net::{StitchClient, StitchNetClient};
4 use std::env;
5
6 #[async_std::main]
7 async fn main() -> anyhow::Result<()> {
8     env_logger::init();
9
10     // get ip address and domain from cmd line args
11     let (ip_addr, domain, cafile_path) = parse_args();
12
13     // construct `rustls` client config
14     let cafile = std::fs::read(cafile_path)?;
15
16     let mut client_pem = std::io::Cursor::new(cafile);
17
18     let mut client_config = ClientConfig::new();
19     client_config
20         .root_store
21         .add_pem_file(&mut client_pem)
22         .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid cert"))?;
23
24     // create a client connection to the server
25     let dist_chan = StitchNetClient::tls_client(ip_addr, &domain, client_config.into())?;
26
27     // create a channel for String messages on the TCP connection
28     let (sender, receiver) = dist_chan.bounded::<String>(Some(100));
29
30     // alert the connection that you are ready to read and write messages
31     dist_chan.ready()?;
32
33     // send a message to the server
34     let msg = String::from("Hello world");
35     info!("Sending message: {}", msg);
36     sender.send(msg).await?;
37
38     // wait for the server to reply with an ack
39     if let Ok(msg) = receiver.recv().await {
40         info!("Received reply: {}", msg);
41     }
42
43     Ok(())
44 }
45
46 fn parse_args() -> (String, String, String) {
47     let args: Vec<String> = env::args().collect();
48
49     let ip_address = match args.get(1) {
50         Some(addr) => addr,
51         None => {
52             error!("Need to pass IP address to connect to as first command line argument");
53             panic!();
54         }
55     };
56
57     let domain = match args.get(2) {
58         Some(d) => d,
59         None => {
60             error!("Need to pass domain name as second command line argument");
61             panic!();
62         }
63     };
64
65     let cafile_path = match args.get(3) {
66         Some(d) => d,
67         None => {
68             error!("Need to pass path to cafile as third command line argument");
69             panic!();
70         }
71     };
72
73     (
74         ip_address.to_string(),
75         domain.to_string(),
76         cafile_path.to_string(),
77     )
78 }