expression
Async connect and accept
The connector and listener create the two endpoints of one connection. Await them concurrently inside the fixture. The listener remains distinct from the accepted stream. Tokio is an external crate. Authorized isolated IPv4 loopback fixture; no public network or DNS. Expected stdout (not executed): true true Common mistake: Treating the listening socket as a connected stream.
Formal Syntax & Structure
rust syntaxrust
TcpStream::connect(addr).await; listener.accept().awaitWorking Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { tokio::time::timeout(std::time::Duration::from_secs(3), async { use tokio::net::{TcpListener, TcpStream}; let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let (client, accepted) = tokio::join!(TcpStream::connect(addr), listener.accept()); let mut client = client.unwrap(); let (mut server, _) = accepted.unwrap(); println!("{}", client.peer_addr().unwrap() == server.local_addr().unwrap()); println!("{}", client.local_addr().unwrap() == server.peer_addr().unwrap()); }).await.expect("fixture deadline");}