1 #![warn(rust_2018_idioms)] 2 #![cfg(feature = "full")] 3 4 use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; 5 use tokio::net::{TcpListener, TcpStream}; 6 use tokio::sync::oneshot; 7 use tokio_test::assert_ok; 8 9 #[tokio::test] echo_server()10async fn echo_server() { 11 const ITER: usize = 1024; 12 13 let (tx, rx) = oneshot::channel(); 14 15 let srv = assert_ok!(TcpListener::bind("127.0.0.1:0").await); 16 let addr = assert_ok!(srv.local_addr()); 17 18 let msg = "foo bar baz"; 19 tokio::spawn(async move { 20 let mut stream = assert_ok!(TcpStream::connect(&addr).await); 21 22 for _ in 0..ITER { 23 // write 24 assert_ok!(stream.write_all(msg.as_bytes()).await); 25 26 // read 27 let mut buf = [0; 11]; 28 assert_ok!(stream.read_exact(&mut buf).await); 29 assert_eq!(&buf[..], msg.as_bytes()); 30 } 31 32 assert_ok!(tx.send(())); 33 }); 34 35 let (mut stream, _) = assert_ok!(srv.accept().await); 36 let (mut rd, mut wr) = stream.split(); 37 38 let n = assert_ok!(io::copy(&mut rd, &mut wr).await); 39 assert_eq!(n, (ITER * msg.len()) as u64); 40 41 assert_ok!(rx.await); 42 } 43