Skip to content

Instantly share code, notes, and snippets.

@bynect
Created July 16, 2025 22:06
Show Gist options
  • Save bynect/f2753fe0978aa6dd1a19b9adc7fa4300 to your computer and use it in GitHub Desktop.
Save bynect/f2753fe0978aa6dd1a19b9adc7fa4300 to your computer and use it in GitHub Desktop.
Basic async proxy in Rust
use std::time::Instant;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::net::TcpStream;
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("0.0.0.0:9000").await.unwrap();
loop {
let (mut client, addr) = listener.accept().await.unwrap();
println!("Client from {}", addr);
let mut server = TcpStream::connect("0.0.0.0:8000").await.unwrap();
println!("Server");
let start = Instant::now();
tokio::spawn(async move {
match tokio::io::copy_bidirectional(&mut client, &mut server).await {
Ok((to_egress, to_ingress)) => {
println!(
"Connection ended gracefully ({to_egress} bytes from client, {to_ingress} bytes from server)"
);
}
Err(err) => {
println!("Error while proxying: {:?}", err);
}
};
println!("TOOK {}ms", start.elapsed().as_millis());
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment