liveBook · Manning

Protocol

As explained in Python Concurrency with asyncio

asyncio.Protocol is the base protocol class for implementing event-driven network communication callbacks in asyncio.

An asyncio.Protocol is a Python class that receives callbacks for network-connection events. It owns connection lifecycle behavior, while a transport sends and receives the underlying data. section 8.1 section 8.2

A protocol commonly responds to these transport events:

  • connection_made receives a transport after the socket connects and can immediately send a request. section 8.2
  • data_received receives response bytes and may run repeatedly, so the protocol must buffer incomplete data. section 8.2
  • eof_received signals the end of the socket response, helping determine when processing is complete. section 8.2

A callback-based HTTP client

Subclass asyncio.Protocol, store a Future and response buffer, send an HTTP GET from connection_made, collect chunks in data_received, and return the completed response through an asynchronous get_response method. A protocol factory supplies the instance to loop.create_connection. section 8.2

Figure 8.2 A transport calls methods on a protocol when events happen. A protocol can write data to a transport.
08-02

The transport–protocol interaction diagram shows transports invoking protocol callbacks and protocols writing data back to transports. section 8.2

How Python Concurrency with asyncio covers it

How deep it goes
Explains subclassing, callback sequencing, repeated data delivery, buffering, end-of-file handling, and protocol factories without descending into socket internals.
Examples
Demonstrates an HTTP GET client and connects standard input to StreamReader through StreamReaderProtocol.
What you can do after
Apply it via asyncio event-loop connection APIs to build callback-driven network clients or asynchronous input readers.
How it connects
Connects protocols with transports, streams, sockets, callbacks, futures, and StreamReader.

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.