std-type
TcpStream: connected TCP byte stream
A connection supplies an ordered byte stream, not records. A successful write is not proof that the peer application processed the bytes. This fixture creates both endpoints of one local connection. Expected stdout (not executed): hi Common mistake: Assuming TCP preserves application message boundaries.
Formal Syntax & Structure
rust syntaxrust
TcpStream::connect(address) -> 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(); } use std::io::{Read, Write}; client.write_all(b"hi").unwrap(); let mut b = [0; 2]; server.read_exact(&mut b).unwrap(); println!("{}", std::str::from_utf8(&b).unwrap());}