std-method
TcpStream::try_clone: shared connection handles
Duplicate a handle to the same socket, not the underlying TCP connection. Reads and writes share the stream and options; concurrent application framing needs coordination. Expected stdout (not executed): true 120 Common mistake: Assuming each clone has a private copy of received bytes.
Formal Syntax & Structure
rust syntaxrust
stream.try_clone() -> io::Result<TcpStream>Working Example
Example Snippetrust
fn main() { use std::{net::{Ipv4Addr, TcpListener, TcpStream}, time::Duration}; let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let mut client = TcpStream::connect_timeout(&listener.local_addr().unwrap(), Duration::from_secs(2)).unwrap(); let (mut server, _) = listener.accept().unwrap(); for s in [&client, &server] { s.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); s.set_write_timeout(Some(Duration::from_secs(2))).unwrap(); } let copy = client.try_clone().unwrap(); println!("{}", copy.peer_addr().unwrap() == client.peer_addr().unwrap()); drop(copy); use std::io::{Read, Write}; client.write_all(b"x").unwrap(); let mut b = [0; 1]; server.read_exact(&mut b).unwrap(); println!("{}", b[0]);}