]> git.lizzy.rs Git - connect-rs.git/blob - examples/tcp-client/src/main.rs
refactor to have datagram already serialized in memory
[connect-rs.git] / examples / tcp-client / src / main.rs
1 use connect::{ConnectDatagram, Connection, SinkExt, StreamExt};
2 use log::*;
3 use std::env;
4
5 #[async_std::main]
6 async fn main() -> anyhow::Result<()> {
7     env_logger::init();
8
9     // Get ip address from cmd line args
10     let args: Vec<String> = env::args().collect();
11     let ip_address = match args.get(1) {
12         Some(addr) => addr,
13         None => {
14             error!("Need to pass IP address to connect to as command line argument");
15             panic!();
16         }
17     };
18
19     // create a client connection to the server
20     let mut conn = Connection::tcp_client(ip_address).await?;
21
22     // send a message to the server
23     let msg = String::from("Hello world");
24     info!("Sending message: {}", msg);
25
26     let envelope = ConnectDatagram::with_tag(65535, msg.into_bytes())?;
27     conn.writer().send(envelope).await?;
28
29     // wait for the server to reply with an ack
30     if let Some(reply) = conn.reader().next().await {
31         let data = reply.data().to_vec();
32         let msg = String::from_utf8(data)?;
33
34         info!("Received message: {}", msg);
35     }
36
37     Ok(())
38 }