]> git.lizzy.rs Git - connect-rs.git/blob - examples/tcp-echo-server/src/main.rs
f480928a872910c376f2216b2ef85a8da2b2bcba
[connect-rs.git] / examples / tcp-echo-server / src / main.rs
1 mod schema;
2
3 use crate::schema::hello_world::HelloWorld;
4 use async_std::task;
5 use connect::tcp::TcpServer;
6 use connect::{SinkExt, StreamExt};
7 use log::*;
8 use std::env;
9
10 #[async_std::main]
11 async fn main() -> anyhow::Result<()> {
12     env_logger::init();
13
14     // Get ip address from cmd line args
15     let args: Vec<String> = env::args().collect();
16
17     let ip_address = match args.get(1) {
18         Some(addr) => addr,
19         None => {
20             error!("Need to pass IP address to bind to as command line argument");
21             panic!();
22         }
23     };
24
25     // create a server
26     let mut server = TcpServer::new(ip_address).await?;
27
28     // handle server connections
29     // wait for a connection to come in and be accepted
30     while let Some(mut conn) = server.next().await {
31         info!("Handling connection from {}", conn.peer_addr());
32
33         task::spawn(async move {
34             while let Some(msg) = conn.reader().next().await {
35                 if msg.is::<HelloWorld>() {
36                     if let Ok(Some(contents)) = msg.unpack::<HelloWorld>() {
37                         info!(
38                             "Received a message \"{}\" from {}",
39                             contents.get_message(),
40                             conn.peer_addr()
41                         );
42
43                         conn.writer()
44                             .send(contents)
45                             .await
46                             .expect("Could not send message back to source connection");
47                         info!("Sent message back to original sender");
48                     }
49                 } else {
50                     error!("Received a message of unknown type")
51                 }
52             }
53         });
54     }
55
56     Ok(())
57 }