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