1 #![warn(rust_2018_idioms)] 2 #![cfg(all(feature = "full", not(target_os = "wasi"), not(miri)))] // Wasi doesn't support bind 3 // No socket on `miri`. 4 5 use std::io::Read; 6 use std::io::Result; 7 use tokio::io::{AsyncReadExt, AsyncWriteExt}; 8 use tokio::net::TcpListener; 9 use tokio::net::TcpStream; 10 11 #[tokio::test] tcp_into_std() -> Result<()>12async fn tcp_into_std() -> Result<()> { 13 let mut data = [0u8; 12]; 14 let listener = TcpListener::bind("127.0.0.1:0").await?; 15 let addr = listener.local_addr().unwrap().to_string(); 16 17 let handle = tokio::spawn(async { 18 let stream: TcpStream = TcpStream::connect(addr).await.unwrap(); 19 stream 20 }); 21 22 let (tokio_tcp_stream, _) = listener.accept().await?; 23 let mut std_tcp_stream = tokio_tcp_stream.into_std()?; 24 std_tcp_stream 25 .set_nonblocking(false) 26 .expect("set_nonblocking call failed"); 27 28 let mut client = handle.await.expect("The task being joined has panicked"); 29 client.write_all(b"Hello world!").await?; 30 31 std_tcp_stream 32 .read_exact(&mut data) 33 .expect("std TcpStream read failed!"); 34 assert_eq!(b"Hello world!", &data); 35 36 // test back to tokio stream 37 std_tcp_stream 38 .set_nonblocking(true) 39 .expect("set_nonblocking call failed"); 40 let mut tokio_tcp_stream = TcpStream::from_std(std_tcp_stream)?; 41 client.write_all(b"Hello tokio!").await?; 42 let _size = tokio_tcp_stream.read_exact(&mut data).await?; 43 assert_eq!(b"Hello tokio!", &data); 44 45 Ok(()) 46 } 47