std-method

TCP read and write timeout configuration

Configure per-operation socket timeouts. They are not total application deadlines; operating systems may round timing and report different error kinds. This example verifies configuration without measuring elapsed wall time. Expected stdout (not executed): true true true Common mistake: Assuming all operating systems report a timed-out read with the same ErrorKind.

Formal Syntax & Structure

rust syntaxrust
stream.set_read_timeout(Some(duration)); stream.set_write_timeout(Some(duration));

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();    }    println!("{} {}", client.read_timeout().unwrap().is_some(), client.write_timeout().unwrap().is_some());    client.set_read_timeout(None).unwrap();    println!("{}", client.read_timeout().unwrap().is_none());}
Rust Reference