Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created August 19, 2022 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/4de2f43798d8a713439a757008d6fe01 to your computer and use it in GitHub Desktop.
Save matthewjberger/4de2f43798d8a713439a757008d6fe01 to your computer and use it in GitHub Desktop.
TCP roundtrip using async_std
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