Graceful Socket Shutdown & The Half-Close Pattern
Calling `sock.close()` tears down both directions immediately. Calling `sock.shutdown(socket.SHUT_WR)` initiates a TCP "Half-Close": sending a `FIN` packet to signal transmission EOF while leaving the inbound receive channel open for the server's response 🤝.
import socket
s1, s2 = socket.socketpair()
# Transmit payload then signal EOF on write channel:
s1.sendall(b"REQUEST_BODY")
s1.shutdown(socket.SHUT_WR)
# Server reads EOF and sends response:
req = s2.recv(1024)
s2.sendall(b"RESPONSE_PAYLOAD")
# Client receives reply despite write shutdown:
reply = s1.recv(1024)
print(f"Reply: {reply.decode()} 🤝")
s1.close()
s2.close()
# 14. Graceful Socket Shutdown & The Half-Close Pattern Calling `sock.close()` tears down both directions immediately. Calling `sock.shutdown(socket.SHUT_WR)` initiates a TCP "Half-Close": sending a `FIN` packet to signal transmission EOF while leaving the inbound receive channel open for the server's response 🤝. ```python import socket s1, s2 = socket.socketpair() # Transmit payload then signal EOF on write channel: s1.sendall(b"REQUEST_BODY") s1.shutdown(socket.SHUT_WR) # Server reads EOF and sends response: req = s2.recv(1024) s2.sendall(b"RESPONSE_PAYLOAD") # Client receives reply despite write shutdown: reply = s1.recv(1024) print(f"Reply: {reply.decode()} 🤝") s1.close() s2.close() ``` Protocols like HTTP/1.0 without `Content-Length` headers rely on `SHUT_WR` to delimit request end. If you call `close()` prematurely, the remote server's reply will trigger an `ECONNRESET` error 🛑! --- ### Question What does `sock.shutdown(socket.SHUT_WR)` transmit across the TCP connection? 🧠 - [ ] a. A TCP FIN packet signaling that write transmission is finished while keeping the read channel active 🤝 - [ ] b. A TCP RST packet that aborts the socket immediately - [ ] c. A SYN packet initiating a new connection sequence - [ ] d. A dummy UDP packet triggering a firewall timeout --- ### Challenge Half-close `s1` with `s1.shutdown(socket.SHUT_WR)`. Send `b'PONG'` from `s2`. Read from `s1`, clean up both sockets, and print the decoded message. 🎯 <details> <summary>Solution</summary> ```python import socket s1, s2 = socket.socketpair() s1.shutdown(socket.SHUT_WR) s2.sendall(b'PONG') msg = s1.recv(1024).decode() s1.close() s2.close() print(msg) ``` </details>