2 use connect::tcp::TcpListener;
3 use connect::{ConnectDatagram, SinkExt, StreamExt};
8 async fn main() -> anyhow::Result<()> {
11 // Get ip address from cmd line args
12 let args: Vec<String> = env::args().collect();
14 let ip_address = match args.get(1) {
17 error!("Need to pass IP address to bind to as command line argument");
23 let mut server = TcpListener::bind(ip_address).await?;
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());
30 task::spawn(async move {
31 while let Some(mut envelope) = conn.reader().next().await {
32 // handle message based on intended recipient
33 if envelope.recipient() == 65535 {
34 // if recipient is 65535, we do custom processing
35 let data = envelope.take_data().unwrap();
37 String::from_utf8(data).expect("could not build String from payload bytes");
38 info!("Received a message \"{}\" from {}", msg, conn.peer_addr());
40 let reply = ConnectDatagram::new(envelope.recipient(), msg.into_bytes())
41 .expect("could not construct new datagram from built String");
46 .expect("Could not send message back to source connection");
47 info!("Sent message back to original sender");
49 // if recipient is anything else, we just send it back
51 "Received a message for unknown recipient {} from {}",
59 .expect("Could not send message back to source connection");
60 info!("Sent message back to original sender");