A non-blocking socket returns immediately from I/O calls instead of waiting for data or a connection. If data is ready, the call returns it; otherwise, the socket reports that no data is available and the application can continue other work. section 1.6.1 section 3.3
Non-blocking sockets change how an application handles waiting:
- Blocking sockets pause the thread during accept or recv, preventing it from serving other clients. section 3.2.2
- Non-blocking sockets let one thread move between connections while the operating system tracks socket readiness. section 1.6.1 section 1.8
- Python creates one by calling setblocking(False); unavailable data can raise BlockingIOError rather than silently waiting. section 3.3
- Repeatedly catching that exception in a tight loop works but can drive CPU usage to 100%; selectors provide more efficient readiness notification. section 3.3 section 3.7
A non-blocking server socket
After creating, binding, and listening on a socket, call server_socket.setblocking(False). The server can then attempt accept without waiting for a client; readiness can be handled through selectors or the asyncio event loop. section 3.3 section 3.7
Figure 1.8 Making a non-blocking I/O request returns immediately and tells the O/S to watch sockets for data. This allows execute_other_code() to run right away instead of waiting for the I/O requests to finish. Later, we can be alerted when I/O is complete and process the response.
Visualizes how a non-blocking request returns immediately, allowing other code to run before the operating system reports completed I/O. section 1.6.1
