]> git.lizzy.rs Git - connect-rs.git/blob - examples/tcp-client-blaster/src/main.rs
improve documentation and logging
[connect-rs.git] / examples / tcp-client-blaster / src / main.rs
1 use connect::{ConnectDatagram, Connection, SinkExt, StreamExt};
2 use log::*;
3 use std::env;
4
5 type Number = u16;
6 const NUM_MESSAGES: Number = 10000;
7
8 #[async_std::main]
9 async fn main() -> anyhow::Result<()> {
10     env_logger::init();
11
12     // Get ip address from cmd line args
13     let args: Vec<String> = env::args().collect();
14     let ip_address = match args.get(1) {
15         Some(addr) => addr,
16         None => {
17             error!("Need to pass IP address to connect to as command line argument");
18             panic!();
19         }
20     };
21
22     // create a client connection to the server
23     let conn = Connection::tcp_client(ip_address).await?;
24     let (mut reader, mut writer) = conn.split();
25
26     // receive messages
27     let read_task = async_std::task::spawn(async move {
28         let mut prev: Option<Number> = None;
29
30         while let Some(mut reply) = reader.next().await {
31             let mut payload = reply.take_data().unwrap();
32
33             let mut data_bytes: [u8; 2] = [0; 2];
34             for i in 0..payload.len() {
35                 data_bytes[i] = payload.remove(0);
36             }
37
38             let data = Number::from_be_bytes(data_bytes);
39
40             if let Some(prev_num) = prev {
41                 assert_eq!(prev_num + 1, data);
42             } else {
43                 assert_eq!(0, data);
44             }
45
46             prev = Some(data);
47             info!("Received message: {}", data);
48
49             if prev.unwrap() + 1 == NUM_MESSAGES {
50                 break;
51             }
52         }
53     });
54
55     // send messages to the server
56     for i in 0..NUM_MESSAGES {
57         info!("Sending message: {}", i);
58         let data = i.to_be_bytes().to_vec();
59         let envelope = ConnectDatagram::new(i, data)?;
60         writer.send(envelope).await?;
61     }
62
63     read_task.await;
64
65     Ok(())
66 }