-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
net: add TcpStream::into_std (#3189)
- Loading branch information
Showing
3 changed files
with
106 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
#![warn(rust_2018_idioms)] | ||
#![cfg(feature = "full")] | ||
|
||
use std::io::Read; | ||
use std::io::Result; | ||
use tokio::io::{AsyncReadExt, AsyncWriteExt}; | ||
use tokio::net::TcpListener; | ||
use tokio::net::TcpStream; | ||
|
||
#[tokio::test] | ||
async fn tcp_into_std() -> Result<()> { | ||
let mut data = [0u8; 12]; | ||
let listener = TcpListener::bind("127.0.0.1:34254").await?; | ||
|
||
let handle = tokio::spawn(async { | ||
let stream: TcpStream = TcpStream::connect("127.0.0.1:34254").await.unwrap(); | ||
stream | ||
}); | ||
|
||
let (tokio_tcp_stream, _) = listener.accept().await?; | ||
let mut std_tcp_stream = tokio_tcp_stream.into_std()?; | ||
std_tcp_stream | ||
.set_nonblocking(false) | ||
.expect("set_nonblocking call failed"); | ||
|
||
let mut client = handle.await.expect("The task being joined has panicked"); | ||
client.write_all(b"Hello world!").await?; | ||
|
||
std_tcp_stream | ||
.read_exact(&mut data) | ||
.expect("std TcpStream read failed!"); | ||
assert_eq!(b"Hello world!", &data); | ||
|
||
// test back to tokio stream | ||
std_tcp_stream | ||
.set_nonblocking(true) | ||
.expect("set_nonblocking call failed"); | ||
let mut tokio_tcp_stream = TcpStream::from_std(std_tcp_stream)?; | ||
client.write_all(b"Hello tokio!").await?; | ||
let _size = tokio_tcp_stream.read_exact(&mut data).await?; | ||
assert_eq!(b"Hello tokio!", &data); | ||
|
||
Ok(()) | ||
} |