Non-Blocking Sockets & The EWOULDBLOCK Protocol
By default, `socket.recv()` stalls the calling thread until network packets arrive. Calling `sock.setblocking(False)` transitions to asynchronous non-blocking I/O: empty reads instantly raise `BlockingIOError` (`EWOULDBLOCK`), freeing the CPU to process other tasks ⚡.
import socket
s1, s2 = socket.socketpair()
s1.setblocking(False)
try:
# Reading from an empty non-blocking buffer raises immediately:
data = s1.recv(1024)
except BlockingIOError as e:
print(f"Non-blocking interrupt: {type(e).__name__} (errno {e.errno}) ⚡")
finally:
s1.close()
s2.close()
# 1. Non-Blocking Sockets & The EWOULDBLOCK Protocol By default, `socket.recv()` stalls the calling thread until network packets arrive. Calling `sock.setblocking(False)` transitions to asynchronous non-blocking I/O: empty reads instantly raise `BlockingIOError` (`EWOULDBLOCK`), freeing the CPU to process other tasks ⚡. ```python import socket s1, s2 = socket.socketpair() s1.setblocking(False) try: # Reading from an empty non-blocking buffer raises immediately: data = s1.recv(1024) except BlockingIOError as e: print(f"Non-blocking interrupt: {type(e).__name__} (errno {e.errno}) ⚡") finally: s1.close() s2.close() ``` Never loop constantly over non-blocking `recv()` calls without multiplexing—a naive `while True: try recv` spins CPU cores at 100% busy-wait utilization! Modern servers pair non-blocking sockets with OS event pollers like `epoll` or `kqueue` 🏎️! --- ### Question What exception does a non-blocking socket raise when `recv()` is invoked on an empty buffer? 🧠 - [ ] a. `BlockingIOError` (wrapping OS errno `EAGAIN` / `EWOULDBLOCK`), signaling that data is not yet available ⚡ - [ ] b. `ConnectionResetError`, indicating the remote client disconnected - [ ] c. `BrokenPipeError`, permanently terminating the socket session - [ ] d. `BufferError`, indicating memory buffer exhaustion --- ### Challenge Create a socket pair with `socket.socketpair()`. Set `s1.setblocking(False)`. Catch `BlockingIOError` on `s1.recv(1024)`, close both sockets, and print `'NONBLOCKING_VERIFIED'`. 🎯 <details> <summary>Solution</summary> ```python import socket s1, s2 = socket.socketpair() s1.setblocking(False) try: s1.recv(1024) except BlockingIOError: print('NONBLOCKING_VERIFIED') finally: s1.close() s2.close() ``` </details>