Created
August 19, 2022 16:54
-
-
Save matthewjberger/4de2f43798d8a713439a757008d6fe01 to your computer and use it in GitHub Desktop.
TCP roundtrip using async_std
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use anyhow::Result; | |
use async_std::{ | |
io, | |
net::{TcpListener, TcpStream}, | |
prelude::*, | |
task, | |
}; | |
fn main() -> Result<()> { | |
task::spawn(async move { | |
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap(); | |
println!("Listening on {}", listener.local_addr().unwrap()); | |
let mut incoming = listener.incoming(); | |
while let Some(stream) = incoming.next().await { | |
let stream = stream.unwrap(); | |
task::spawn(async { | |
println!("Accepted from: {}", stream.peer_addr().unwrap()); | |
let mut reader = stream.clone(); | |
let mut writer = stream; | |
io::copy(&mut reader, &mut writer).await.unwrap(); | |
}); | |
} | |
}); | |
task::block_on(async { | |
let mut stream = TcpStream::connect("127.0.0.1:8080").await?; | |
println!("Connected to {}", &stream.peer_addr()?); | |
let msg = "hello world"; | |
println!("<- {}", msg); | |
stream.write_all(msg.as_bytes()).await?; | |
let mut buf = vec![0u8; 1024]; | |
let n = stream.read(&mut buf).await?; | |
println!("-> {}\n", String::from_utf8_lossy(&buf[..n])); | |
Ok(()) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment