How to Handle Network Timeouts in Rust
Handle network timeouts in Rust by wrapping blocking I/O calls with connect_timeout or set_read_timeout using std::time::Duration.
use std::net::{TcpStream, SocketAddr};
use std::time::Duration;
fn main() {
let socket_addr: SocketAddr = "127.0.0.1:7878".parse().unwrap();
let stream = TcpStream::connect_timeout(&socket_addr, Duration::from_secs(5));
match stream {
Ok(mut s) => {
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
// Proceed with I/O
}
Err(e) => eprintln!("Connection timed out or failed: {}", e),
}
}
For async code, use tokio::time::timeout with tokio::net::TcpStream to enforce limits without blocking threads.