liveBook · Manning

Non-blocking socket

As explained in Python Concurrency with asyncio

A socket operating mode in which I/O calls return without waiting for the operation to complete.

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.
01-08

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

How Python Concurrency with asyncio covers it

How deep it goes
Explains blocking contrasts, configuration, readiness errors, polling costs, selectors, and event-loop integration, but not socket internals.
Examples
Demonstrates a multi-client echo server, setblocking(False), BlockingIOError polling, selectors, and aiohttp-based web requests.
What it assumes
Assumes basic sockets and I/O knowledge while contrasting blocking behavior and introducing event-loop concurrency progressively.
What you can do after
Build it from scratch by configuring sockets, handling readiness, and integrating them with selectors or asyncio for concurrent clients.
How it connects
Connects non-blocking sockets to I/O-bound work, concurrency, selectors, event loops, coroutines, tasks, and asyncio.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.