Python 3.4+Async programmingterm
asyncio.Protocol
protocols and transports
The protocol for a stream connection (TCP, Unix socket, SSL): the loop calls data_received() for every chunk of bytes and eof_received() at the end.
Syntax
transport, protocol = await loop.create_connection(ProtocolClass, host, port)
Learners rarely need this layer: streams (asyncio.open_connection() and asyncio.start_server()) cover TCP, and asyncio.create_subprocess_exec() covers processes. The main trap: data_received() knows nothing about message boundaries — one sent message may arrive in two chunks and two may arrive as one, so buffering and delimiter search are yours to write (StreamReader ships readline() and readuntil()). A protocol pays off only when you need raw speed without extra coroutines.
Examples
import asyncio
import socket
class Echo(asyncio.Protocol):
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
print('получено', data) # → получено b'ping'
self.transport.write(data.upper())
async def main():
loop = asyncio.get_running_loop()
left, right = socket.socketpair() # локальная пара сокетов вместо сети
transport, proto = await loop.create_connection(Echo, sock=left)
right.sendall(b'ping')
await asyncio.sleep(0.01)
print(right.recv(10)) # → b'PING'
transport.close()
right.close()
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy