Created
July 16, 2025 22:06
-
-
Save bynect/f2753fe0978aa6dd1a19b9adc7fa4300 to your computer and use it in GitHub Desktop.
Basic async proxy in Rust
This file contains hidden or 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 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