18.5.4.Transports and protocols (callback based API)

Source code:Lib/asyncio/transports.py

Source code:Lib/asyncio/protocols.py

18.5.4.1.Transports

Transports are classes provided byasyncio in order to abstractvarious kinds of communication channels. You generally won’t instantiatea transport yourself; instead, you will call anAbstractEventLoop methodwhich will create the transport and try to initiate the underlyingcommunication channel, calling you back when it succeeds.

Once the communication channel is established, a transport is alwayspaired with aprotocol instance. The protocol canthen call the transport’s methods for various purposes.

asyncio currently implements transports for TCP, UDP, SSL, andsubprocess pipes. The methods available on a transport depend onthe transport’s kind.

The transport classes arenot thread safe.

Changed in version 3.6:The socket optionTCP_NODELAY is now set by default.

18.5.4.1.1.BaseTransport

classasyncio.BaseTransport

Base class for transports.

close()

Close the transport. If the transport has a buffer for outgoingdata, buffered data will be flushed asynchronously. No more datawill be received. After all buffered data is flushed, theprotocol’sconnection_lost() method will be called withNone as its argument.

is_closing()

ReturnTrue if the transport is closing or is closed.

New in version 3.5.1.

get_extra_info(name,default=None)

Return optional transport information.name is a string representingthe piece of transport-specific information to get,default is thevalue to return if the information doesn’t exist.

This method allows transport implementations to easily exposechannel-specific information.

set_protocol(protocol)

Set a new protocol. Switching protocol should only be done when bothprotocols are documented to support the switch.

New in version 3.5.3.

get_protocol()

Return the current protocol.

New in version 3.5.3.

Changed in version 3.5.1:'ssl_object' info was added to SSL sockets.

18.5.4.1.2.ReadTransport

classasyncio.ReadTransport

Interface for read-only transports.

pause_reading()

Pause the receiving end of the transport. No data will be passed tothe protocol’sdata_received() method untilresume_reading()is called.

Changed in version 3.6.7:The method is idempotent, i.e. it can be called when thetransport is already paused or closed.

resume_reading()

Resume the receiving end. The protocol’sdata_received() methodwill be called once again if some data is available for reading.

Changed in version 3.6.7:The method is idempotent, i.e. it can be called when thetransport is already reading.

18.5.4.1.3.WriteTransport

classasyncio.WriteTransport

Interface for write-only transports.

abort()

Close the transport immediately, without waiting for pending operationsto complete. Buffered data will be lost. No more data will be received.The protocol’sconnection_lost() method will eventually becalled withNone as its argument.

can_write_eof()

ReturnTrue if the transport supportswrite_eof(),False if not.

get_write_buffer_size()

Return the current size of the output buffer used by the transport.

get_write_buffer_limits()

Get thehigh- andlow-water limits for write flow control. Return atuple(low,high) wherelow andhigh are positive number ofbytes.

Useset_write_buffer_limits() to set the limits.

New in version 3.4.2.

set_write_buffer_limits(high=None,low=None)

Set thehigh- andlow-water limits for write flow control.

These two values (measured in number ofbytes) control when the protocol’spause_writing() andresume_writing() methods are called.If specified, the low-water limit must be less than or equal to thehigh-water limit. Neitherhigh norlow can be negative.

pause_writing() is called when the buffer size becomes greaterthan or equal to thehigh value. If writing has been paused,resume_writing() is called when the buffer size becomes lessthan or equal to thelow value.

The defaults are implementation-specific. If only thehigh-water limit is given, the low-water limit defaults to animplementation-specific value less than or equal to thehigh-water limit. Settinghigh to zero forceslow to zero aswell, and causespause_writing() to be called whenever thebuffer becomes non-empty. Settinglow to zero causesresume_writing() to be called only once the buffer is empty.Use of zero for either limit is generally sub-optimal as itreduces opportunities for doing I/O and computationconcurrently.

Useget_write_buffer_limits() to get the limits.

write(data)

Write somedata bytes to the transport.

This method does not block; it buffers the data and arranges for itto be sent out asynchronously.

writelines(list_of_data)

Write a list (or any iterable) of data bytes to the transport.This is functionally equivalent to callingwrite() on eachelement yielded by the iterable, but may be implemented more efficiently.

write_eof()

Close the write end of the transport after flushing buffered data.Data may still be received.

This method can raiseNotImplementedError if the transport(e.g. SSL) doesn’t support half-closes.

18.5.4.1.4.DatagramTransport

DatagramTransport.sendto(data,addr=None)

Send thedata bytes to the remote peer given byaddr (atransport-dependent target address). Ifaddr isNone, thedata is sent to the target address given on transport creation.

This method does not block; it buffers the data and arranges for itto be sent out asynchronously.

DatagramTransport.abort()

Close the transport immediately, without waiting for pending operationsto complete. Buffered data will be lost. No more data will be received.The protocol’sconnection_lost() method will eventually becalled withNone as its argument.

18.5.4.1.5.BaseSubprocessTransport

classasyncio.BaseSubprocessTransport
get_pid()

Return the subprocess process id as an integer.

get_pipe_transport(fd)

Return the transport for the communication pipe corresponding to theinteger file descriptorfd:

  • 0: readable streaming transport of the standard input (stdin),orNone if the subprocess was not created withstdin=PIPE

  • 1: writable streaming transport of the standard output (stdout),orNone if the subprocess was not created withstdout=PIPE

  • 2: writable streaming transport of the standard error (stderr),orNone if the subprocess was not created withstderr=PIPE

  • otherfd:None

get_returncode()

Return the subprocess returncode as an integer orNoneif it hasn’t returned, similarly to thesubprocess.Popen.returncode attribute.

kill()

Kill the subprocess, as insubprocess.Popen.kill().

On POSIX systems, the function sends SIGKILL to the subprocess.On Windows, this method is an alias forterminate().

send_signal(signal)

Send thesignal number to the subprocess, as insubprocess.Popen.send_signal().

terminate()

Ask the subprocess to stop, as insubprocess.Popen.terminate().This method is an alias for theclose() method.

On POSIX systems, this method sends SIGTERM to the subprocess.On Windows, the Windows API function TerminateProcess() is called tostop the subprocess.

close()

Ask the subprocess to stop by calling theterminate() method if thesubprocess hasn’t returned yet, and close transports of all pipes(stdin,stdout andstderr).

18.5.4.2.Protocols

asyncio provides base classes that you can subclass to implementyour network protocols. Those classes are used in conjunction withtransports (see below): the protocol parses incomingdata and asks for the writing of outgoing data, while the transport isresponsible for the actual I/O and buffering.

When subclassing a protocol class, it is recommended you override certainmethods. Those methods are callbacks: they will be called by the transporton certain events (for example when some data is received); you shouldn’tcall them yourself, unless you are implementing a transport.

Note

All callbacks have default implementations, which are empty. Therefore,you only need to implement the callbacks for the events in which youare interested.

18.5.4.2.1.Protocol classes

classasyncio.Protocol

The base class for implementing streaming protocols (for use withe.g. TCP and SSL transports).

classasyncio.DatagramProtocol

The base class for implementing datagram protocols (for use withe.g. UDP transports).

classasyncio.SubprocessProtocol

The base class for implementing protocols communicating with childprocesses (through a set of unidirectional pipes).

18.5.4.2.2.Connection callbacks

These callbacks may be called onProtocol,DatagramProtocolandSubprocessProtocol instances:

BaseProtocol.connection_made(transport)

Called when a connection is made.

Thetransport argument is the transport representing theconnection. You are responsible for storing it somewhere(e.g. as an attribute) if you need to.

BaseProtocol.connection_lost(exc)

Called when the connection is lost or closed.

The argument is either an exception object orNone.The latter means a regular EOF is received, or the connection wasaborted or closed by this side of the connection.

connection_made() andconnection_lost()are called exactly once per successful connection. All other callbacks will becalled between those two methods, which allows for easier resource managementin your protocol implementation.

The following callbacks may be called only onSubprocessProtocolinstances:

SubprocessProtocol.pipe_data_received(fd,data)

Called when the child process writes data into its stdout or stderr pipe.fd is the integer file descriptor of the pipe.data is a non-emptybytes object containing the data.

SubprocessProtocol.pipe_connection_lost(fd,exc)

Called when one of the pipes communicating with the child processis closed.fd is the integer file descriptor that was closed.

SubprocessProtocol.process_exited()

Called when the child process has exited.

18.5.4.2.3.Streaming protocols

The following callbacks are called onProtocol instances:

Protocol.data_received(data)

Called when some data is received.data is a non-empty bytes objectcontaining the incoming data.

Note

Whether the data is buffered, chunked or reassembled depends onthe transport. In general, you shouldn’t rely on specific semanticsand instead make your parsing generic and flexible enough. However,data is always received in the correct order.

Protocol.eof_received()

Called when the other end signals it won’t send any more data(for example by callingwrite_eof(), if the other end also usesasyncio).

This method may return a false value (includingNone), in which casethe transport will close itself. Conversely, if this method returns atrue value, closing the transport is up to the protocol. Since thedefault implementation returnsNone, it implicitly closes the connection.

Note

Some transports such as SSL don’t support half-closed connections,in which case returning true from this method will not prevent closingthe connection.

data_received() can be called an arbitrary number of times duringa connection. However,eof_received() is called at most onceand, if called,data_received() won’t be called after it.

State machine:

18.5.4.2.4.Datagram protocols

The following callbacks are called onDatagramProtocol instances.

DatagramProtocol.datagram_received(data,addr)

Called when a datagram is received.data is a bytes object containingthe incoming data.addr is the address of the peer sending the data;the exact format depends on the transport.

DatagramProtocol.error_received(exc)

Called when a previous send or receive operation raises anOSError.exc is theOSError instance.

This method is called in rare conditions, when the transport (e.g. UDP)detects that a datagram couldn’t be delivered to its recipient.In many conditions though, undeliverable datagrams will be silentlydropped.

18.5.4.2.5.Flow control callbacks

These callbacks may be called onProtocol,DatagramProtocol andSubprocessProtocol instances:

BaseProtocol.pause_writing()

Called when the transport’s buffer goes over the high-water mark.

BaseProtocol.resume_writing()

Called when the transport’s buffer drains below the low-water mark.

pause_writing() andresume_writing() calls are paired –pause_writing() is called once when the buffer goes strictly overthe high-water mark (even if subsequent writes increases the buffer sizeeven more), and eventuallyresume_writing() is called once when thebuffer size reaches the low-water mark.

Note

If the buffer size equals the high-water mark,pause_writing() is not called – it must go strictly over.Conversely,resume_writing() is called when the buffer size isequal or lower than the low-water mark. These end conditionsare important to ensure that things go as expected when eithermark is zero.

Note

On BSD systems (OS X, FreeBSD, etc.) flow control is not supportedforDatagramProtocol, because send failures caused bywriting too many packets cannot be detected easily. The socketalways appears ‘ready’ and excess packets are dropped; anOSError with errno set toerrno.ENOBUFS may ormay not be raised; if it is raised, it will be reported toDatagramProtocol.error_received() but otherwise ignored.

18.5.4.2.6.Coroutines and protocols

Coroutines can be scheduled in a protocol method usingensure_future(),but there is no guarantee made about the execution order. Protocols are notaware of coroutines created in protocol methods and so will not wait for them.

To have a reliable execution order, usestream objects in acoroutine withyieldfrom. For example, theStreamWriter.drain()coroutine can be used to wait until the write buffer is flushed.

18.5.4.3.Protocol examples

18.5.4.3.1.TCP echo client protocol

TCP echo client using theAbstractEventLoop.create_connection() method, senddata and wait until the connection is closed:

importasyncioclassEchoClientProtocol(asyncio.Protocol):def__init__(self,message,loop):self.message=messageself.loop=loopdefconnection_made(self,transport):transport.write(self.message.encode())print('Data sent:{!r}'.format(self.message))defdata_received(self,data):print('Data received:{!r}'.format(data.decode()))defconnection_lost(self,exc):print('The server closed the connection')print('Stop the event loop')self.loop.stop()loop=asyncio.get_event_loop()message='Hello World!'coro=loop.create_connection(lambda:EchoClientProtocol(message,loop),'127.0.0.1',8888)loop.run_until_complete(coro)loop.run_forever()loop.close()

The event loop is running twice. Therun_until_complete() method is preferred in this shortexample to raise an exception if the server is not listening, instead ofhaving to write a short coroutine to handle the exception and stop therunning loop. Atrun_until_complete() exit, the loop isno longer running, so there is no need to stop the loop in case of an error.

See also

TheTCP echo client using streamsexample uses theasyncio.open_connection() function.

18.5.4.3.2.TCP echo server protocol

TCP echo server using theAbstractEventLoop.create_server() method, send backreceived data and close the connection:

importasyncioclassEchoServerClientProtocol(asyncio.Protocol):defconnection_made(self,transport):peername=transport.get_extra_info('peername')print('Connection from{}'.format(peername))self.transport=transportdefdata_received(self,data):message=data.decode()print('Data received:{!r}'.format(message))print('Send:{!r}'.format(message))self.transport.write(data)print('Close the client socket')self.transport.close()loop=asyncio.get_event_loop()# Each client connection will create a new protocol instancecoro=loop.create_server(EchoServerClientProtocol,'127.0.0.1',8888)server=loop.run_until_complete(coro)# Serve requests until Ctrl+C is pressedprint('Serving on{}'.format(server.sockets[0].getsockname()))try:loop.run_forever()exceptKeyboardInterrupt:pass# Close the serverserver.close()loop.run_until_complete(server.wait_closed())loop.close()

Transport.close() can be called immediately afterWriteTransport.write() even if data are not sent yet on the socket: bothmethods are asynchronous.yieldfrom is not needed because these transportmethods are not coroutines.

See also

TheTCP echo server using streamsexample uses theasyncio.start_server() function.

18.5.4.3.3.UDP echo client protocol

UDP echo client using theAbstractEventLoop.create_datagram_endpoint()method, send data and close the transport when we received the answer:

importasyncioclassEchoClientProtocol:def__init__(self,message,loop):self.message=messageself.loop=loopself.transport=Nonedefconnection_made(self,transport):self.transport=transportprint('Send:',self.message)self.transport.sendto(self.message.encode())defdatagram_received(self,data,addr):print("Received:",data.decode())print("Close the socket")self.transport.close()deferror_received(self,exc):print('Error received:',exc)defconnection_lost(self,exc):print("Socket closed, stop the event loop")loop=asyncio.get_event_loop()loop.stop()loop=asyncio.get_event_loop()message="Hello World!"connect=loop.create_datagram_endpoint(lambda:EchoClientProtocol(message,loop),remote_addr=('127.0.0.1',9999))transport,protocol=loop.run_until_complete(connect)loop.run_forever()transport.close()loop.close()

18.5.4.3.4.UDP echo server protocol

UDP echo server using theAbstractEventLoop.create_datagram_endpoint()method, send back received data:

importasyncioclassEchoServerProtocol:defconnection_made(self,transport):self.transport=transportdefdatagram_received(self,data,addr):message=data.decode()print('Received%r from%s'%(message,addr))print('Send%r to%s'%(message,addr))self.transport.sendto(data,addr)loop=asyncio.get_event_loop()print("Starting UDP server")# One protocol instance will be created to serve all client requestslisten=loop.create_datagram_endpoint(EchoServerProtocol,local_addr=('127.0.0.1',9999))transport,protocol=loop.run_until_complete(listen)try:loop.run_forever()exceptKeyboardInterrupt:passtransport.close()loop.close()

18.5.4.3.5.Register an open socket to wait for data using a protocol

Wait until a socket receives data using theAbstractEventLoop.create_connection() method with a protocol, and then closethe event loop

importasynciotry:fromsocketimportsocketpairexceptImportError:fromasyncio.windows_utilsimportsocketpair# Create a pair of connected socketsrsock,wsock=socketpair()loop=asyncio.get_event_loop()classMyProtocol(asyncio.Protocol):transport=Nonedefconnection_made(self,transport):self.transport=transportdefdata_received(self,data):print("Received:",data.decode())# We are done: close the transport (it will call connection_lost())self.transport.close()defconnection_lost(self,exc):# The socket has been closed, stop the event looploop.stop()# Register the socket to wait for dataconnect_coro=loop.create_connection(MyProtocol,sock=rsock)transport,protocol=loop.run_until_complete(connect_coro)# Simulate the reception of data from the networkloop.call_soon(wsock.send,'abc'.encode())# Run the event looploop.run_forever()# We are done, close sockets and the event looprsock.close()wsock.close()loop.close()

See also

Thewatch a file descriptor for read events example uses the low-levelAbstractEventLoop.add_reader() method to register the file descriptor of asocket.

Theregister an open socket to wait for data using streams example uses high-level streamscreated by theopen_connection() function in a coroutine.