Socket Timeouts & Non-Blocking Sockets
By default, sockets block indefinitely on `.recv()`. Use `sock.settimeout(seconds)` to raise `socket.timeout`, or `sock.setblocking(False)` for non-blocking I/O ⏱️.
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.5) # Raises socket.timeout after 1.5s ⏱️
print(f"Timeout configured: {sock.gettimeout()}s")
sock.close()
# 74. Socket Timeouts & Non-Blocking Sockets By default, sockets block indefinitely on `.recv()`. Use `sock.settimeout(seconds)` to raise `socket.timeout`, or `sock.setblocking(False)` for non-blocking I/O ⏱️. ```python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1.5) # Raises socket.timeout after 1.5s ⏱️ print(f"Timeout configured: {sock.gettimeout()}s") sock.close() ``` In non-blocking mode (`sock.setblocking(False)`), operations raise `BlockingIOError` immediately if data isn't ready, allowing event loops to poll via `select`! ⏱️ --- ### Question What exception is raised when a socket operation exceeds its configured `.settimeout()` duration? 🧠 - [ ] a. `TimeoutError` (or `socket.timeout`) ⏱️ - [ ] b. `ConnectionRefusedError` - [ ] c. `BrokenPipeError` - [ ] d. `OverflowError` --- ### Challenge Create a socket, set its timeout to `0.25` seconds using `sock.settimeout(0.25)`. Print `sock.gettimeout()`. Close the socket. 🎯 <details> <summary>Solution</summary> ```python import socket s = socket.socket() s.settimeout(0.25) print(s.gettimeout()) s.close() ``` </details>