From 6aca07bee745c8a1f8ddc1c0f27732dec9d3cdb2 Mon Sep 17 00:00:00 2001 From: kiron1 Date: Fri, 28 Jul 2023 18:06:44 +0800 Subject: [PATCH] example: use `copy_bidirectional` in proxy.rs (#5856) --- examples/proxy.rs | 42 ++++++++++++------------------------------ 1 file changed, 12 insertions(+), 30 deletions(-) diff --git a/examples/proxy.rs b/examples/proxy.rs index e5cd4b8b5..9260a12fb 100644 --- a/examples/proxy.rs +++ b/examples/proxy.rs @@ -22,8 +22,7 @@ #![warn(rust_2018_idioms)] -use tokio::io; -use tokio::io::AsyncWriteExt; +use tokio::io::copy_bidirectional; use tokio::net::{TcpListener, TcpStream}; use futures::FutureExt; @@ -44,36 +43,19 @@ async fn main() -> Result<(), Box> { let listener = TcpListener::bind(listen_addr).await?; - while let Ok((inbound, _)) = listener.accept().await { - let transfer = transfer(inbound, server_addr.clone()).map(|r| { - if let Err(e) = r { - println!("Failed to transfer; error={}", e); - } - }); + while let Ok((mut inbound, _)) = listener.accept().await { + let mut outbound = TcpStream::connect(server_addr.clone()).await?; - tokio::spawn(transfer); + tokio::spawn(async move { + copy_bidirectional(&mut inbound, &mut outbound) + .map(|r| { + if let Err(e) = r { + println!("Failed to transfer; error={}", e); + } + }) + .await + }); } Ok(()) } - -async fn transfer(mut inbound: TcpStream, proxy_addr: String) -> Result<(), Box> { - let mut outbound = TcpStream::connect(proxy_addr).await?; - - let (mut ri, mut wi) = inbound.split(); - let (mut ro, mut wo) = outbound.split(); - - let client_to_server = async { - io::copy(&mut ri, &mut wo).await?; - wo.shutdown().await - }; - - let server_to_client = async { - io::copy(&mut ro, &mut wi).await?; - wi.shutdown().await - }; - - tokio::try_join!(client_to_server, server_to_client)?; - - Ok(()) -}