1 #![warn(rust_2018_idioms)] 2 #![cfg(feature = "full")] 3 4 use tokio::net::TcpListener; 5 use tokio_test::assert_ok; 6 7 use std::io::prelude::*; 8 use std::net::TcpStream; 9 use std::thread; 10 11 #[tokio::test] echo_server()12async fn echo_server() { 13 const N: usize = 1024; 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 20 let t = thread::spawn(move || { 21 let mut s = assert_ok!(TcpStream::connect(&addr)); 22 23 let t2 = thread::spawn(move || { 24 let mut s = assert_ok!(TcpStream::connect(&addr)); 25 let mut b = vec![0; msg.len() * N]; 26 assert_ok!(s.read_exact(&mut b)); 27 b 28 }); 29 30 let mut expected = Vec::<u8>::new(); 31 for _i in 0..N { 32 expected.extend(msg.as_bytes()); 33 let res = assert_ok!(s.write(msg.as_bytes())); 34 assert_eq!(res, msg.len()); 35 } 36 37 (expected, t2) 38 }); 39 40 let (mut a, _) = assert_ok!(srv.accept().await); 41 let (mut b, _) = assert_ok!(srv.accept().await); 42 43 let n = assert_ok!(tokio::io::copy(&mut a, &mut b).await); 44 45 let (expected, t2) = t.join().unwrap(); 46 let actual = t2.join().unwrap(); 47 48 assert!(expected == actual); 49 assert_eq!(n, msg.len() as u64 * 1024); 50 } 51