]> git.lizzy.rs Git - connect-rs.git/blob - examples/tcp-echo-server/src/main.rs
refactor to have datagram already serialized in memory
[connect-rs.git] / examples / tcp-echo-server / src / main.rs
1 use async_std::task;
2 use connect::tcp::TcpListener;
3 use connect::{ConnectDatagram, SinkExt, StreamExt};
4 use log::*;
5 use std::env;
6
7 #[async_std::main]
8 async fn main() -> anyhow::Result<()> {
9     env_logger::init();
10
11     // Get ip address from cmd line args
12     let args: Vec<String> = env::args().collect();
13
14     let ip_address = match args.get(1) {
15         Some(addr) => addr,
16         None => {
17             error!("Need to pass IP address to bind to as command line argument");
18             panic!();
19         }
20     };
21
22     // create a server
23     let mut server = TcpListener::bind(ip_address).await?;
24
25     // handle server connections
26     // wait for a connection to come in and be accepted
27     while let Some(mut conn) = server.next().await {
28         info!("Handling connection from {}", conn.peer_addr());
29
30         task::spawn(async move {
31             while let Some(envelope) = conn.reader().next().await {
32                 // handle message based on intended recipient
33                 if envelope.tag() == 65535 {
34                     // if recipient is 65535, we do custom processing
35                     let data = envelope.data().to_vec();
36                     let msg =
37                         String::from_utf8(data).expect("could not build String from payload bytes");
38                     info!("Received a message \"{}\" from {}", msg, conn.peer_addr());
39
40                     let reply = ConnectDatagram::with_tag(envelope.tag(), msg.into_bytes())
41                         .expect("could not construct new datagram from built String");
42
43                     conn.writer()
44                         .send(reply)
45                         .await
46                         .expect("Could not send message back to source connection");
47                     info!("Sent message back to original sender");
48                 } else {
49                     // if recipient is anything else, we just send it back
50                     warn!(
51                         "Received a message for unknown recipient {} from {}",
52                         envelope.tag(),
53                         conn.peer_addr()
54                     );
55
56                     conn.writer()
57                         .send(envelope)
58                         .await
59                         .expect("Could not send message back to source connection");
60                     info!("Sent message back to original sender");
61                 }
62             }
63         });
64     }
65
66     Ok(())
67 }