std-method
TCP half-close with Shutdown::Write
Finish the sending half of a connection while preserving the receiving half. The peer can read already-sent bytes, then observe end-of-stream. Closing the write half does not itself close both directions. Expected stdout (not executed): done 0 ok Common mistake: Assuming a write half-close prevents receiving the peer response.
Formal Syntax & Structure
rust syntaxrust
stream.shutdown(Shutdown::Write) -> io::Result<()>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}, net::Shutdown}; client.write_all(b"done").unwrap(); client.shutdown(Shutdown::Write).unwrap(); let mut bytes = [0; 4]; server.read_exact(&mut bytes).unwrap(); let mut extra = [0; 1]; println!("{} {}", std::str::from_utf8(&bytes).unwrap(), server.read(&mut extra).unwrap()); server.write_all(b"ok").unwrap(); let mut reply = [0; 2]; client.read_exact(&mut reply).unwrap(); println!("{}", std::str::from_utf8(&reply).unwrap());}