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:34254").await?; 14 15 let handle = tokio::spawn(async { 16 let stream: TcpStream = TcpStream::connect("127.0.0.1:34254").await.unwrap(); 17 stream 18 }); 19 20 let (tokio_tcp_stream, _) = listener.accept().await?; 21 let mut std_tcp_stream = tokio_tcp_stream.into_std()?; 22 std_tcp_stream 23 .set_nonblocking(false) 24 .expect("set_nonblocking call failed"); 25 26 let mut client = handle.await.expect("The task being joined has panicked"); 27 client.write_all(b"Hello world!").await?; 28 29 std_tcp_stream 30 .read_exact(&mut data) 31 .expect("std TcpStream read failed!"); 32 assert_eq!(b"Hello world!", &data); 33 34 // test back to tokio stream 35 std_tcp_stream 36 .set_nonblocking(true) 37 .expect("set_nonblocking call failed"); 38 let mut tokio_tcp_stream = TcpStream::from_std(std_tcp_stream)?; 39 client.write_all(b"Hello tokio!").await?; 40 let _size = tokio_tcp_stream.read_exact(&mut data).await?; 41 assert_eq!(b"Hello tokio!", &data); 42 43 Ok(()) 44 } 45