]> git.lizzy.rs Git - connect-rs.git/blob - examples/tcp-client/src/main.rs
make async-oriented, remove block_on
[connect-rs.git] / examples / tcp-client / src / main.rs
1 pub mod schema;
2
3 use crate::schema::hello_world::HelloWorld;
4 use connect::{Connection, SinkExt, StreamExt};
5 use log::*;
6 use protobuf::well_known_types::Any;
7 use std::env;
8
9 #[async_std::main]
10 async fn main() -> anyhow::Result<()> {
11     env_logger::init();
12
13     // Get ip address from cmd line args
14     let args: Vec<String> = env::args().collect();
15     let ip_address = match args.get(1) {
16         Some(addr) => addr,
17         None => {
18             error!("Need to pass IP address to connect to as command line argument");
19             panic!();
20         }
21     };
22
23     // create a client connection to the server
24     let mut conn = Connection::tcp_client(ip_address).await?;
25
26     // send a message to the server
27     let raw_msg = String::from("Hello world");
28
29     let mut msg = HelloWorld::new();
30     msg.set_message(raw_msg.clone());
31
32     conn.writer().send(msg).await?;
33     info!("Sent message: {}", raw_msg);
34
35     // wait for the server to reply with an ack
36     while let Some(reply) = conn.reader().next().await {
37         info!("Received message");
38
39         let msg: HelloWorld = Any::unpack(&reply)?.unwrap();
40
41         info!("Unpacked reply: {}", msg.get_message());
42     }
43
44     Ok(())
45 }