blob: 9dbd3ab46a3f681bc31aadde0479495a0df1d811 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
lf627d2c82017-07-25 17:03:51 -06003
Yury Selivanov3faaa882018-09-14 13:32:07 -07004.. _asyncio-transports-protocols:
5
6
Yury Selivanov7c7605f2018-09-11 09:54:40 -07007========================
8Transports and Protocols
9========================
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov7c7605f2018-09-11 09:54:40 -070011.. rubric:: Preface
12
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040013Transports and Protocols are used by the **low-level** event loop
14APIs such as :meth:`loop.create_connection`. They use
Yury Selivanov7c7605f2018-09-11 09:54:40 -070015callback-based programming style and enable high-performance
16implementations of network or IPC protocols (e.g. HTTP).
17
18Essentially, transports and protocols should only be used in
19libraries and frameworks and never in high-level asyncio
20applications.
21
22This documentation page covers both `Transports`_ and `Protocols`_.
23
24.. rubric:: Introduction
25
26At the highest level, the transport is concerned with *how* bytes
27are transmitted, while the protocol determines *which* bytes to
28transmit (and to some extent when).
29
30A different way of saying the same thing: a transport is an
31abstraction for a socket (or similar I/O endpoint) while a protocol
32is an abstraction for an application, from the transport's point
33of view.
34
Carol Willingc9d66f02018-09-14 10:06:55 -070035Yet another view is the transport and protocol interfaces
Yury Selivanov7c7605f2018-09-11 09:54:40 -070036together define an abstract interface for using network I/O and
37interprocess I/O.
38
39There is always a 1:1 relationship between transport and protocol
40objects: the protocol calls transport methods to send data,
41while the transport calls protocol methods to pass it data that
42has been received.
43
44Most of connection oriented event loop methods
45(such as :meth:`loop.create_connection`) usually accept a
46*protocol_factory* argument used to create a *Protocol* object
47for an accepted connection, represented by a *Transport* object.
48Such methods usually return a tuple of ``(transport, protocol)``.
49
50.. rubric:: Contents
51
52This documentation page contains the following sections:
53
54* The `Transports`_ section documents asyncio :class:`BaseTransport`,
55 :class:`ReadTransport`, :class:`WriteTransport`, :class:`Transport`,
56 :class:`DatagramTransport`, and :class:`SubprocessTransport`
57 classes.
58
59* The `Protocols`_ section documents asyncio :class:`BaseProtocol`,
60 :class:`Protocol`, :class:`BufferedProtocol`,
61 :class:`DatagramProtocol`, and :class:`SubprocessProtocol` classes.
62
63* The `Examples`_ section showcases how to work with transports,
64 protocols, and low-level event loop APIs.
65
Victor Stinner1ca5ba62013-12-03 01:49:43 +010066
Victor Stinner9592edb2014-02-02 15:03:02 +010067.. _asyncio-transport:
Victor Stinnerea3183f2013-12-03 01:08:00 +010068
69Transports
70==========
71
Kyle Stanleyf9000642019-10-10 19:18:46 -040072**Source code:** :source:`Lib/asyncio/transports.py`
73
74----------------------------------------------------
75
Guido van Rossum589872c2014-03-29 21:14:04 -070076Transports are classes provided by :mod:`asyncio` in order to abstract
Yury Selivanov7c7605f2018-09-11 09:54:40 -070077various kinds of communication channels.
Victor Stinnerea3183f2013-12-03 01:08:00 +010078
Yury Selivanov7c7605f2018-09-11 09:54:40 -070079Transport objects are always instantiated by an
Pablo Galindo5033e312019-02-10 00:21:37 +000080:ref:`asyncio event loop <asyncio-event-loop>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010081
Yury Selivanov7c7605f2018-09-11 09:54:40 -070082asyncio implements transports for TCP, UDP, SSL, and subprocess pipes.
83The methods available on a transport depend on the transport's kind.
Victor Stinnerea3183f2013-12-03 01:08:00 +010084
Victor Stinner83704962015-02-25 14:24:15 +010085The transport classes are :ref:`not thread safe <asyncio-multithreading>`.
86
Yury Selivanov3432f2f2016-12-12 16:44:58 -050087
Yury Selivanov7c7605f2018-09-11 09:54:40 -070088Transports Hierarchy
89--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010090
91.. class:: BaseTransport
92
Yury Selivanov7c7605f2018-09-11 09:54:40 -070093 Base class for all transports. Contains methods that all
94 asyncio transports share.
Victor Stinnerea3183f2013-12-03 01:08:00 +010095
Yury Selivanov7c7605f2018-09-11 09:54:40 -070096.. class:: WriteTransport(BaseTransport)
Victor Stinnerea3183f2013-12-03 01:08:00 +010097
Yury Selivanov7c7605f2018-09-11 09:54:40 -070098 A base transport for write-only connections.
Victor Stinnerea3183f2013-12-03 01:08:00 +010099
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700100 Instances of the *WriteTransport* class are returned from
101 the :meth:`loop.connect_write_pipe` event loop method and
102 are also used by subprocess-related methods like
103 :meth:`loop.subprocess_exec`.
Yury Selivanov1744d532015-11-16 12:46:41 -0500104
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700105.. class:: ReadTransport(BaseTransport)
Yury Selivanov1744d532015-11-16 12:46:41 -0500106
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700107 A base transport for read-only connections.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100108
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700109 Instances of the *ReadTransport* class are returned from
110 the :meth:`loop.connect_read_pipe` event loop method and
111 are also used by subprocess-related methods like
112 :meth:`loop.subprocess_exec`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700114.. class:: Transport(WriteTransport, ReadTransport)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100115
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700116 Interface representing a bidirectional transport, such as a
117 TCP connection.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100118
Carol Willingc9d66f02018-09-14 10:06:55 -0700119 The user does not instantiate a transport directly; they call a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700120 utility function, passing it a protocol factory and other
121 information necessary to create the transport and protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100122
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700123 Instances of the *Transport* class are returned from or used by
124 event loop methods like :meth:`loop.create_connection`,
125 :meth:`loop.create_unix_connection`,
126 :meth:`loop.create_server`, :meth:`loop.sendfile`, etc.
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200127
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700129.. class:: DatagramTransport(BaseTransport)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100130
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700131 A transport for datagram (UDP) connections.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100132
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700133 Instances of the *DatagramTransport* class are returned from
134 the :meth:`loop.create_datagram_endpoint` event loop method.
Yury Selivanovd757aaf2017-12-18 17:03:23 -0500135
Victor Stinnerea3183f2013-12-03 01:08:00 +0100136
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700137.. class:: SubprocessTransport(BaseTransport)
138
139 An abstraction to represent a connection between a parent and its
140 child OS process.
141
142 Instances of the *SubprocessTransport* class are returned from
143 event loop methods :meth:`loop.subprocess_shell` and
144 :meth:`loop.subprocess_exec`.
145
146
147Base Transport
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100148--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100149
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700150.. method:: BaseTransport.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100151
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700152 Close the transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100153
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700154 If the transport has a buffer for outgoing
155 data, buffered data will be flushed asynchronously. No more data
156 will be received. After all buffered data is flushed, the
157 protocol's :meth:`protocol.connection_lost()
158 <BaseProtocol.connection_lost>` method will be called with
159 :const:`None` as its argument.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100160
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700161.. method:: BaseTransport.is_closing()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100162
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700163 Return ``True`` if the transport is closing or is closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100164
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700165.. method:: BaseTransport.get_extra_info(name, default=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100166
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700167 Return information about the transport or underlying resources
168 it uses.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100169
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700170 *name* is a string representing the piece of transport-specific
171 information to get.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100172
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700173 *default* is the value to return if the information is not
174 available, or if the transport does not support querying it
175 with the given third-party event loop implementation or on the
176 current platform.
Victor Stinner52bb9492014-08-26 00:22:28 +0200177
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700178 For example, the following code attempts to get the underlying
179 socket object of the transport::
Victor Stinner52bb9492014-08-26 00:22:28 +0200180
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700181 sock = transport.get_extra_info('socket')
182 if sock is not None:
183 print(sock.getsockopt(...))
Victor Stinner52bb9492014-08-26 00:22:28 +0200184
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700185 Categories of information that can be queried on some transports:
Victor Stinner52bb9492014-08-26 00:22:28 +0200186
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700187 * socket:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100188
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700189 - ``'peername'``: the remote address to which the socket is
190 connected, result of :meth:`socket.socket.getpeername`
191 (``None`` on error)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100192
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700193 - ``'socket'``: :class:`socket.socket` instance
Victor Stinnerea3183f2013-12-03 01:08:00 +0100194
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700195 - ``'sockname'``: the socket's own address,
196 result of :meth:`socket.socket.getsockname`
Kojo Idrissa5200a7c2017-06-20 14:32:00 -0500197
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700198 * SSL socket:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100199
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700200 - ``'compression'``: the compression algorithm being used as a
201 string, or ``None`` if the connection isn't compressed; result
202 of :meth:`ssl.SSLSocket.compression`
Victor Stinner52bb9492014-08-26 00:22:28 +0200203
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700204 - ``'cipher'``: a three-value tuple containing the name of the
205 cipher being used, the version of the SSL protocol that defines
206 its use, and the number of secret bits being used; result of
207 :meth:`ssl.SSLSocket.cipher`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100208
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700209 - ``'peercert'``: peer certificate; result of
210 :meth:`ssl.SSLSocket.getpeercert`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100211
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700212 - ``'sslcontext'``: :class:`ssl.SSLContext` instance
Victor Stinnerea3183f2013-12-03 01:08:00 +0100213
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700214 - ``'ssl_object'``: :class:`ssl.SSLObject` or
215 :class:`ssl.SSLSocket` instance
Victor Stinnerea3183f2013-12-03 01:08:00 +0100216
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700217 * pipe:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700219 - ``'pipe'``: pipe object
Victor Stinnerea3183f2013-12-03 01:08:00 +0100220
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700221 * subprocess:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100222
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700223 - ``'subprocess'``: :class:`subprocess.Popen` instance
224
225.. method:: BaseTransport.set_protocol(protocol)
226
227 Set a new protocol.
228
229 Switching protocol should only be done when both
230 protocols are documented to support the switch.
231
232.. method:: BaseTransport.get_protocol()
233
234 Return the current protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100235
236
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700237Read-only Transports
238--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100239
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700240.. method:: ReadTransport.is_reading()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100241
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700242 Return ``True`` if the transport is receiving new data.
243
244 .. versionadded:: 3.7
245
246.. method:: ReadTransport.pause_reading()
247
248 Pause the receiving end of the transport. No data will be passed to
249 the protocol's :meth:`protocol.data_received() <Protocol.data_received>`
250 method until :meth:`resume_reading` is called.
251
252 .. versionchanged:: 3.7
253 The method is idempotent, i.e. it can be called when the
254 transport is already paused or closed.
255
256.. method:: ReadTransport.resume_reading()
257
258 Resume the receiving end. The protocol's
259 :meth:`protocol.data_received() <Protocol.data_received>` method
260 will be called once again if some data is available for reading.
261
262 .. versionchanged:: 3.7
263 The method is idempotent, i.e. it can be called when the
264 transport is already reading.
265
266
267Write-only Transports
268---------------------
269
270.. method:: WriteTransport.abort()
271
272 Close the transport immediately, without waiting for pending operations
273 to complete. Buffered data will be lost. No more data will be received.
274 The protocol's :meth:`protocol.connection_lost()
275 <BaseProtocol.connection_lost>` method will eventually be
276 called with :const:`None` as its argument.
277
278.. method:: WriteTransport.can_write_eof()
279
280 Return :const:`True` if the transport supports
281 :meth:`~WriteTransport.write_eof`, :const:`False` if not.
282
283.. method:: WriteTransport.get_write_buffer_size()
284
285 Return the current size of the output buffer used by the transport.
286
287.. method:: WriteTransport.get_write_buffer_limits()
288
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400289 Get the *high* and *low* watermarks for write flow control. Return a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700290 tuple ``(low, high)`` where *low* and *high* are positive number of
291 bytes.
292
293 Use :meth:`set_write_buffer_limits` to set the limits.
294
295 .. versionadded:: 3.4.2
296
297.. method:: WriteTransport.set_write_buffer_limits(high=None, low=None)
298
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400299 Set the *high* and *low* watermarks for write flow control.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700300
301 These two values (measured in number of
302 bytes) control when the protocol's
303 :meth:`protocol.pause_writing() <BaseProtocol.pause_writing>`
304 and :meth:`protocol.resume_writing() <BaseProtocol.resume_writing>`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400305 methods are called. If specified, the low watermark must be less
306 than or equal to the high watermark. Neither *high* nor *low*
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700307 can be negative.
308
309 :meth:`~BaseProtocol.pause_writing` is called when the buffer size
310 becomes greater than or equal to the *high* value. If writing has
311 been paused, :meth:`~BaseProtocol.resume_writing` is called when
312 the buffer size becomes less than or equal to the *low* value.
313
314 The defaults are implementation-specific. If only the
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400315 high watermark is given, the low watermark defaults to an
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700316 implementation-specific value less than or equal to the
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400317 high watermark. Setting *high* to zero forces *low* to zero as
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700318 well, and causes :meth:`~BaseProtocol.pause_writing` to be called
319 whenever the buffer becomes non-empty. Setting *low* to zero causes
320 :meth:`~BaseProtocol.resume_writing` to be called only once the
321 buffer is empty. Use of zero for either limit is generally
322 sub-optimal as it reduces opportunities for doing I/O and
323 computation concurrently.
324
325 Use :meth:`~WriteTransport.get_write_buffer_limits`
326 to get the limits.
327
328.. method:: WriteTransport.write(data)
329
330 Write some *data* bytes to the transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100331
332 This method does not block; it buffers the data and arranges for it
333 to be sent out asynchronously.
334
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700335.. method:: WriteTransport.writelines(list_of_data)
336
337 Write a list (or any iterable) of data bytes to the transport.
338 This is functionally equivalent to calling :meth:`write` on each
339 element yielded by the iterable, but may be implemented more
340 efficiently.
341
342.. method:: WriteTransport.write_eof()
343
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400344 Close the write end of the transport after flushing all buffered data.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700345 Data may still be received.
346
347 This method can raise :exc:`NotImplementedError` if the transport
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400348 (e.g. SSL) doesn't support half-closed connections.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700349
350
351Datagram Transports
352-------------------
353
354.. method:: DatagramTransport.sendto(data, addr=None)
355
356 Send the *data* bytes to the remote peer given by *addr* (a
357 transport-dependent target address). If *addr* is :const:`None`,
358 the data is sent to the target address given on transport
359 creation.
360
361 This method does not block; it buffers the data and arranges
362 for it to be sent out asynchronously.
363
Victor Stinnerea3183f2013-12-03 01:08:00 +0100364.. method:: DatagramTransport.abort()
365
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700366 Close the transport immediately, without waiting for pending
367 operations to complete. Buffered data will be lost.
368 No more data will be received. The protocol's
369 :meth:`protocol.connection_lost() <BaseProtocol.connection_lost>`
370 method will eventually be called with :const:`None` as its argument.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100371
372
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700373.. _asyncio-subprocess-transports:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100374
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700375Subprocess Transports
376---------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100377
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700378.. method:: SubprocessTransport.get_pid()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100379
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700380 Return the subprocess process id as an integer.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100381
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700382.. method:: SubprocessTransport.get_pipe_transport(fd)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100383
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700384 Return the transport for the communication pipe corresponding to the
385 integer file descriptor *fd*:
Victor Stinner4270a242014-10-13 23:56:43 +0200386
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700387 * ``0``: readable streaming transport of the standard input (*stdin*),
388 or :const:`None` if the subprocess was not created with ``stdin=PIPE``
389 * ``1``: writable streaming transport of the standard output (*stdout*),
390 or :const:`None` if the subprocess was not created with ``stdout=PIPE``
391 * ``2``: writable streaming transport of the standard error (*stderr*),
392 or :const:`None` if the subprocess was not created with ``stderr=PIPE``
393 * other *fd*: :const:`None`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100394
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700395.. method:: SubprocessTransport.get_returncode()
Victor Stinner933a8c82013-12-03 01:59:38 +0100396
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700397 Return the subprocess return code as an integer or :const:`None`
Carol Willingc9d66f02018-09-14 10:06:55 -0700398 if it hasn't returned, which is similar to the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700399 :attr:`subprocess.Popen.returncode` attribute.
Victor Stinner933a8c82013-12-03 01:59:38 +0100400
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700401.. method:: SubprocessTransport.kill()
Victor Stinner933a8c82013-12-03 01:59:38 +0100402
Yury Selivanov3faaa882018-09-14 13:32:07 -0700403 Kill the subprocess.
Victor Stinner933a8c82013-12-03 01:59:38 +0100404
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700405 On POSIX systems, the function sends SIGKILL to the subprocess.
406 On Windows, this method is an alias for :meth:`terminate`.
Victor Stinner933a8c82013-12-03 01:59:38 +0100407
Yury Selivanov3faaa882018-09-14 13:32:07 -0700408 See also :meth:`subprocess.Popen.kill`.
409
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700410.. method:: SubprocessTransport.send_signal(signal)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700412 Send the *signal* number to the subprocess, as in
413 :meth:`subprocess.Popen.send_signal`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100414
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700415.. method:: SubprocessTransport.terminate()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100416
Yury Selivanov3faaa882018-09-14 13:32:07 -0700417 Stop the subprocess.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100418
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700419 On POSIX systems, this method sends SIGTERM to the subprocess.
420 On Windows, the Windows API function TerminateProcess() is called to
421 stop the subprocess.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100422
Yury Selivanov3faaa882018-09-14 13:32:07 -0700423 See also :meth:`subprocess.Popen.terminate`.
424
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700425.. method:: SubprocessTransport.close()
Victor Stinner4270a242014-10-13 23:56:43 +0200426
Yury Selivanov3faaa882018-09-14 13:32:07 -0700427 Kill the subprocess by calling the :meth:`kill` method.
428
429 If the subprocess hasn't returned yet, and close transports of
430 *stdin*, *stdout*, and *stderr* pipes.
Victor Stinner4270a242014-10-13 23:56:43 +0200431
Victor Stinnerea3183f2013-12-03 01:08:00 +0100432
Victor Stinner9592edb2014-02-02 15:03:02 +0100433.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100434
435Protocols
436=========
437
Kyle Stanleyf9000642019-10-10 19:18:46 -0400438**Source code:** :source:`Lib/asyncio/protocols.py`
439
440---------------------------------------------------
441
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700442asyncio provides a set of abstract base classes that should be used
443to implement network protocols. Those classes are meant to be used
444together with :ref:`transports <asyncio-transport>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100445
Carol Willingc9d66f02018-09-14 10:06:55 -0700446Subclasses of abstract base protocol classes may implement some or
447all methods. All these methods are callbacks: they are called by
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700448transports on certain events, for example when some data is received.
Carol Willingc9d66f02018-09-14 10:06:55 -0700449A base protocol method should be called by the corresponding transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
451
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700452Base Protocols
453--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100454
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700455.. class:: BaseProtocol
Victor Stinnerea3183f2013-12-03 01:08:00 +0100456
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700457 Base protocol with methods that all protocols share.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100458
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700459.. class:: Protocol(BaseProtocol)
460
461 The base class for implementing streaming protocols
462 (TCP, Unix sockets, etc).
463
464.. class:: BufferedProtocol(BaseProtocol)
Yury Selivanov631fd382018-01-28 16:30:26 -0500465
466 A base class for implementing streaming protocols with manual
467 control of the receive buffer.
468
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700469.. class:: DatagramProtocol(BaseProtocol)
Yury Selivanov631fd382018-01-28 16:30:26 -0500470
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700471 The base class for implementing datagram (UDP) protocols.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100472
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700473.. class:: SubprocessProtocol(BaseProtocol)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100474
475 The base class for implementing protocols communicating with child
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700476 processes (unidirectional pipes).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100477
478
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700479Base Protocol
480-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100481
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482All asyncio protocols can implement Base Protocol callbacks.
483
484.. rubric:: Connection Callbacks
485
486Connection callbacks are called on all protocols, exactly once per
487a successful connection. All other protocol callbacks can only be
488called between those two methods.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100489
490.. method:: BaseProtocol.connection_made(transport)
491
492 Called when a connection is made.
493
494 The *transport* argument is the transport representing the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700495 connection. The protocol is responsible for storing the reference
496 to its transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100497
498.. method:: BaseProtocol.connection_lost(exc)
499
500 Called when the connection is lost or closed.
501
502 The argument is either an exception object or :const:`None`.
503 The latter means a regular EOF is received, or the connection was
504 aborted or closed by this side of the connection.
505
Victor Stinnerea3183f2013-12-03 01:08:00 +0100506
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700507.. rubric:: Flow Control Callbacks
Victor Stinnerea3183f2013-12-03 01:08:00 +0100508
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700509Flow control callbacks can be called by transports to pause or
510resume writing performed by the protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100511
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700512See the documentation of the :meth:`~WriteTransport.set_write_buffer_limits`
513method for more details.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100514
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700515.. method:: BaseProtocol.pause_writing()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100516
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400517 Called when the transport's buffer goes over the high watermark.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100518
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700519.. method:: BaseProtocol.resume_writing()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100520
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400521 Called when the transport's buffer drains below the low watermark.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700522
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400523If the buffer size equals the high watermark,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700524:meth:`~BaseProtocol.pause_writing` is not called: the buffer size must
525go strictly over.
526
527Conversely, :meth:`~BaseProtocol.resume_writing` is called when the
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400528buffer size is equal or lower than the low watermark. These end
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700529conditions are important to ensure that things go as expected when
530either mark is zero.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100531
532
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700533Streaming Protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100534-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100535
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700536Event methods, such as :meth:`loop.create_server`,
537:meth:`loop.create_unix_server`, :meth:`loop.create_connection`,
538:meth:`loop.create_unix_connection`, :meth:`loop.connect_accepted_socket`,
539:meth:`loop.connect_read_pipe`, and :meth:`loop.connect_write_pipe`
540accept factories that return streaming protocols.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100541
542.. method:: Protocol.data_received(data)
543
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700544 Called when some data is received. *data* is a non-empty bytes
545 object containing the incoming data.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100546
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700547 Whether the data is buffered, chunked or reassembled depends on
548 the transport. In general, you shouldn't rely on specific semantics
Carol Willingc9d66f02018-09-14 10:06:55 -0700549 and instead make your parsing generic and flexible. However,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700550 data is always received in the correct order.
551
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400552 The method can be called an arbitrary number of times while
553 a connection is open.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700554
555 However, :meth:`protocol.eof_received() <Protocol.eof_received>`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400556 is called at most once. Once `eof_received()` is called,
557 ``data_received()`` is not called anymore.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100558
559.. method:: Protocol.eof_received()
560
Barry Warsawdd9a0a12017-04-07 14:18:14 -0400561 Called when the other end signals it won't send any more data
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700562 (for example by calling :meth:`transport.write_eof()
563 <WriteTransport.write_eof>`, if the other end also uses
Victor Stinnerea3183f2013-12-03 01:08:00 +0100564 asyncio).
565
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300566 This method may return a false value (including ``None``), in which case
Victor Stinnerea3183f2013-12-03 01:08:00 +0100567 the transport will close itself. Conversely, if this method returns a
Carol Willingc9d66f02018-09-14 10:06:55 -0700568 true value, the protocol used determines whether to close the transport.
569 Since the default implementation returns ``None``, it implicitly closes the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700570 connection.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100571
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400572 Some transports, including SSL, don't support half-closed connections,
573 in which case returning true from this method will result in the connection
574 being closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100575
Victor Stinnerea3183f2013-12-03 01:08:00 +0100576
Victor Stinner54a231d2015-01-29 13:33:15 +0100577State machine:
578
Yury Selivanov631fd382018-01-28 16:30:26 -0500579.. code-block:: none
580
581 start -> connection_made
582 [-> data_received]*
583 [-> eof_received]?
584 -> connection_lost -> end
585
586
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700587Buffered Streaming Protocols
588----------------------------
Yury Selivanov631fd382018-01-28 16:30:26 -0500589
590.. versionadded:: 3.7
Yury Selivanov631fd382018-01-28 16:30:26 -0500591
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700592Buffered Protocols can be used with any event loop method
593that supports `Streaming Protocols`_.
Yury Selivanov631fd382018-01-28 16:30:26 -0500594
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400595``BufferedProtocol`` implementations allow explicit manual allocation
Carol Willingc9d66f02018-09-14 10:06:55 -0700596and control of the receive buffer. Event loops can then use the buffer
Yury Selivanov631fd382018-01-28 16:30:26 -0500597provided by the protocol to avoid unnecessary data copies. This
598can result in noticeable performance improvement for protocols that
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400599receive big amounts of data. Sophisticated protocol implementations
600can significantly reduce the number of buffer allocations.
Yury Selivanov631fd382018-01-28 16:30:26 -0500601
602The following callbacks are called on :class:`BufferedProtocol`
603instances:
604
Yury Selivanovdbf10222018-05-28 14:31:28 -0400605.. method:: BufferedProtocol.get_buffer(sizehint)
Yury Selivanov631fd382018-01-28 16:30:26 -0500606
Yury Selivanovdbf10222018-05-28 14:31:28 -0400607 Called to allocate a new receive buffer.
608
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400609 *sizehint* is the recommended minimum size for the returned
610 buffer. It is acceptable to return smaller or larger buffers
Yury Selivanovdbf10222018-05-28 14:31:28 -0400611 than what *sizehint* suggests. When set to -1, the buffer size
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400612 can be arbitrary. It is an error to return a buffer with a zero size.
Yury Selivanovdbf10222018-05-28 14:31:28 -0400613
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400614 ``get_buffer()`` must return an object implementing the
Yury Selivanovdbf10222018-05-28 14:31:28 -0400615 :ref:`buffer protocol <bufferobjects>`.
Yury Selivanov631fd382018-01-28 16:30:26 -0500616
617.. method:: BufferedProtocol.buffer_updated(nbytes)
618
619 Called when the buffer was updated with the received data.
620
621 *nbytes* is the total number of bytes that were written to the buffer.
622
623.. method:: BufferedProtocol.eof_received()
624
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700625 See the documentation of the :meth:`protocol.eof_received()
626 <Protocol.eof_received>` method.
Yury Selivanov631fd382018-01-28 16:30:26 -0500627
628
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700629:meth:`~BufferedProtocol.get_buffer` can be called an arbitrary number
630of times during a connection. However, :meth:`protocol.eof_received()
631<Protocol.eof_received>` is called at most once
632and, if called, :meth:`~BufferedProtocol.get_buffer` and
633:meth:`~BufferedProtocol.buffer_updated` won't be called after it.
Yury Selivanov631fd382018-01-28 16:30:26 -0500634
635State machine:
636
637.. code-block:: none
638
639 start -> connection_made
640 [-> get_buffer
641 [-> buffer_updated]?
642 ]*
643 [-> eof_received]?
644 -> connection_lost -> end
Victor Stinner54a231d2015-01-29 13:33:15 +0100645
646
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700647Datagram Protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100648------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100649
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700650Datagram Protocol instances should be constructed by protocol
651factories passed to the :meth:`loop.create_datagram_endpoint` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100652
653.. method:: DatagramProtocol.datagram_received(data, addr)
654
655 Called when a datagram is received. *data* is a bytes object containing
656 the incoming data. *addr* is the address of the peer sending the data;
657 the exact format depends on the transport.
658
659.. method:: DatagramProtocol.error_received(exc)
660
661 Called when a previous send or receive operation raises an
662 :class:`OSError`. *exc* is the :class:`OSError` instance.
663
664 This method is called in rare conditions, when the transport (e.g. UDP)
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400665 detects that a datagram could not be delivered to its recipient.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100666 In many conditions though, undeliverable datagrams will be silently
667 dropped.
668
Victor Stinnerea3183f2013-12-03 01:08:00 +0100669.. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100670
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700671 On BSD systems (macOS, FreeBSD, etc.) flow control is not supported
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400672 for datagram protocols, because there is no reliable way to detect send
Carol Willingc9d66f02018-09-14 10:06:55 -0700673 failures caused by writing too many packets.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700674
Carol Willingc9d66f02018-09-14 10:06:55 -0700675 The socket always appears 'ready' and excess packets are dropped. An
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700676 :class:`OSError` with ``errno`` set to :const:`errno.ENOBUFS` may
677 or may not be raised; if it is raised, it will be reported to
Larry Hastings3732ed22014-03-15 21:13:56 -0700678 :meth:`DatagramProtocol.error_received` but otherwise ignored.
679
Victor Stinnerea3183f2013-12-03 01:08:00 +0100680
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700681.. _asyncio-subprocess-protocols:
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100682
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700683Subprocess Protocols
684--------------------
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100685
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700686Datagram Protocol instances should be constructed by protocol
687factories passed to the :meth:`loop.subprocess_exec` and
688:meth:`loop.subprocess_shell` methods.
689
690.. method:: SubprocessProtocol.pipe_data_received(fd, data)
691
692 Called when the child process writes data into its stdout or stderr
693 pipe.
694
695 *fd* is the integer file descriptor of the pipe.
696
697 *data* is a non-empty bytes object containing the received data.
698
699.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
700
701 Called when one of the pipes communicating with the child process
702 is closed.
703
704 *fd* is the integer file descriptor that was closed.
705
706.. method:: SubprocessProtocol.process_exited()
707
708 Called when the child process has exited.
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100709
710
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700711Examples
712========
Victor Stinnered051592014-10-12 20:18:16 +0200713
Yury Selivanov394374e2018-09-17 15:35:24 -0400714.. _asyncio_example_tcp_echo_server_protocol:
Victor Stinnered051592014-10-12 20:18:16 +0200715
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700716TCP Echo Server
717---------------
Victor Stinnered051592014-10-12 20:18:16 +0200718
Carol Willingc9d66f02018-09-14 10:06:55 -0700719Create a TCP echo server using the :meth:`loop.create_server` method, send back
720received data, and close the connection::
Victor Stinnera881a7f2013-12-09 13:19:23 +0100721
722 import asyncio
723
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700724
Braden Groom43a5bd72018-10-15 14:39:16 -0700725 class EchoServerProtocol(asyncio.Protocol):
Victor Stinnera881a7f2013-12-09 13:19:23 +0100726 def connection_made(self, transport):
727 peername = transport.get_extra_info('peername')
Victor Stinnerc2721b42014-10-12 11:13:40 +0200728 print('Connection from {}'.format(peername))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100729 self.transport = transport
730
731 def data_received(self, data):
Victor Stinnerc2721b42014-10-12 11:13:40 +0200732 message = data.decode()
733 print('Data received: {!r}'.format(message))
734
735 print('Send: {!r}'.format(message))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100736 self.transport.write(data)
737
Victor Stinner53664342014-10-12 11:35:09 +0200738 print('Close the client socket')
Victor Stinnera881a7f2013-12-09 13:19:23 +0100739 self.transport.close()
740
Victor Stinnera881a7f2013-12-09 13:19:23 +0100741
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700742 async def main():
743 # Get a reference to the event loop as we plan to use
744 # low-level APIs.
745 loop = asyncio.get_running_loop()
Victor Stinnerc2721b42014-10-12 11:13:40 +0200746
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700747 server = await loop.create_server(
Braden Groom43a5bd72018-10-15 14:39:16 -0700748 lambda: EchoServerProtocol(),
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700749 '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100750
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700751 async with server:
752 await server.serve_forever()
753
754
755 asyncio.run(main())
756
Victor Stinnera881a7f2013-12-09 13:19:23 +0100757
Victor Stinnered051592014-10-12 20:18:16 +0200758.. seealso::
759
760 The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700761 example uses the high-level :func:`asyncio.start_server` function.
762
Yury Selivanov394374e2018-09-17 15:35:24 -0400763.. _asyncio_example_tcp_echo_client_protocol:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700764
765TCP Echo Client
766---------------
767
Carol Willingc9d66f02018-09-14 10:06:55 -0700768A TCP echo client using the :meth:`loop.create_connection` method, sends
769data, and waits until the connection is closed::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700770
771 import asyncio
772
773
774 class EchoClientProtocol(asyncio.Protocol):
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200775 def __init__(self, message, on_con_lost):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700776 self.message = message
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700777 self.on_con_lost = on_con_lost
778
779 def connection_made(self, transport):
780 transport.write(self.message.encode())
781 print('Data sent: {!r}'.format(self.message))
782
783 def data_received(self, data):
784 print('Data received: {!r}'.format(data.decode()))
785
786 def connection_lost(self, exc):
787 print('The server closed the connection')
788 self.on_con_lost.set_result(True)
789
790
791 async def main():
792 # Get a reference to the event loop as we plan to use
793 # low-level APIs.
794 loop = asyncio.get_running_loop()
795
796 on_con_lost = loop.create_future()
797 message = 'Hello World!'
798
799 transport, protocol = await loop.create_connection(
Hrvoje Nikšić5d359cc2019-09-17 09:16:43 +0200800 lambda: EchoClientProtocol(message, on_con_lost),
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700801 '127.0.0.1', 8888)
802
803 # Wait until the protocol signals that the connection
804 # is lost and close the transport.
805 try:
806 await on_con_lost
807 finally:
808 transport.close()
809
810
811 asyncio.run(main())
812
813
814.. seealso::
815
816 The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700817 example uses the high-level :func:`asyncio.open_connection` function.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700818
819
820.. _asyncio-udp-echo-server-protocol:
821
822UDP Echo Server
823---------------
824
Carol Willingc9d66f02018-09-14 10:06:55 -0700825A UDP echo server, using the :meth:`loop.create_datagram_endpoint`
826method, sends back received data::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700827
828 import asyncio
829
830
831 class EchoServerProtocol:
832 def connection_made(self, transport):
833 self.transport = transport
834
835 def datagram_received(self, data, addr):
836 message = data.decode()
837 print('Received %r from %s' % (message, addr))
838 print('Send %r to %s' % (message, addr))
839 self.transport.sendto(data, addr)
840
841
842 async def main():
843 print("Starting UDP server")
844
845 # Get a reference to the event loop as we plan to use
846 # low-level APIs.
847 loop = asyncio.get_running_loop()
848
849 # One protocol instance will be created to serve all
850 # client requests.
851 transport, protocol = await loop.create_datagram_endpoint(
852 lambda: EchoServerProtocol(),
853 local_addr=('127.0.0.1', 9999))
854
855 try:
856 await asyncio.sleep(3600) # Serve for 1 hour.
857 finally:
858 transport.close()
859
860
861 asyncio.run(main())
Victor Stinnered051592014-10-12 20:18:16 +0200862
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200863
864.. _asyncio-udp-echo-client-protocol:
865
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700866UDP Echo Client
867---------------
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200868
Carol Willingc9d66f02018-09-14 10:06:55 -0700869A UDP echo client, using the :meth:`loop.create_datagram_endpoint`
870method, sends data and closes the transport when it receives the answer::
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200871
872 import asyncio
873
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700874
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200875 class EchoClientProtocol:
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200876 def __init__(self, message, on_con_lost):
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200877 self.message = message
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200878 self.on_con_lost = on_con_lost
Hrvoje Nikšić5d359cc2019-09-17 09:16:43 +0200879 self.transport = None
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200880
881 def connection_made(self, transport):
882 self.transport = transport
883 print('Send:', self.message)
884 self.transport.sendto(self.message.encode())
885
886 def datagram_received(self, data, addr):
887 print("Received:", data.decode())
888
889 print("Close the socket")
890 self.transport.close()
891
892 def error_received(self, exc):
893 print('Error received:', exc)
894
895 def connection_lost(self, exc):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700896 print("Connection closed")
897 self.on_con_lost.set_result(True)
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200898
899
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700900 async def main():
901 # Get a reference to the event loop as we plan to use
902 # low-level APIs.
903 loop = asyncio.get_running_loop()
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200904
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200905 on_con_lost = loop.create_future()
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700906 message = "Hello World!"
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200907
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700908 transport, protocol = await loop.create_datagram_endpoint(
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200909 lambda: EchoClientProtocol(message, on_con_lost),
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700910 remote_addr=('127.0.0.1', 9999))
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200911
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700912 try:
Hrvoje Nikšićc717c732019-09-15 19:06:02 +0200913 await on_con_lost
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700914 finally:
915 transport.close()
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200916
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200917
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700918 asyncio.run(main())
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200919
920
Yury Selivanov394374e2018-09-17 15:35:24 -0400921.. _asyncio_example_create_connection:
Victor Stinnera881a7f2013-12-09 13:19:23 +0100922
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700923Connecting Existing Sockets
924---------------------------
Victor Stinner04e6df32014-10-11 16:16:27 +0200925
926Wait until a socket receives data using the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700927:meth:`loop.create_connection` method with a protocol::
Victor Stinner04e6df32014-10-11 16:16:27 +0200928
929 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700930 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200931
Victor Stinner04e6df32014-10-11 16:16:27 +0200932
933 class MyProtocol(asyncio.Protocol):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700934
Hrvoje Nikšić5d359cc2019-09-17 09:16:43 +0200935 def __init__(self, on_con_lost):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700936 self.transport = None
Hrvoje Nikšić5d359cc2019-09-17 09:16:43 +0200937 self.on_con_lost = on_con_lost
Victor Stinner04e6df32014-10-11 16:16:27 +0200938
939 def connection_made(self, transport):
940 self.transport = transport
941
942 def data_received(self, data):
943 print("Received:", data.decode())
944
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700945 # We are done: close the transport;
946 # connection_lost() will be called automatically.
Victor Stinner04e6df32014-10-11 16:16:27 +0200947 self.transport.close()
948
949 def connection_lost(self, exc):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700950 # The socket has been closed
951 self.on_con_lost.set_result(True)
Victor Stinner04e6df32014-10-11 16:16:27 +0200952
Victor Stinner04e6df32014-10-11 16:16:27 +0200953
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700954 async def main():
955 # Get a reference to the event loop as we plan to use
956 # low-level APIs.
957 loop = asyncio.get_running_loop()
Hrvoje Nikšić5d359cc2019-09-17 09:16:43 +0200958 on_con_lost = loop.create_future()
Victor Stinner04e6df32014-10-11 16:16:27 +0200959
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700960 # Create a pair of connected sockets
961 rsock, wsock = socket.socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200962
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700963 # Register the socket to wait for data.
964 transport, protocol = await loop.create_connection(
Hrvoje Nikšić5d359cc2019-09-17 09:16:43 +0200965 lambda: MyProtocol(on_con_lost), sock=rsock)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700966
967 # Simulate the reception of data from the network.
968 loop.call_soon(wsock.send, 'abc'.encode())
969
970 try:
971 await protocol.on_con_lost
972 finally:
973 transport.close()
974 wsock.close()
975
976 asyncio.run(main())
Victor Stinner04e6df32014-10-11 16:16:27 +0200977
978.. seealso::
979
980 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400981 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700982 :meth:`loop.add_reader` method to register an FD.
Victor Stinner04e6df32014-10-11 16:16:27 +0200983
984 The :ref:`register an open socket to wait for data using streams
Yury Selivanov394374e2018-09-17 15:35:24 -0400985 <asyncio_example_create_connection-streams>` example uses high-level streams
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700986 created by the :func:`open_connection` function in a coroutine.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700987
Yury Selivanov394374e2018-09-17 15:35:24 -0400988.. _asyncio_example_subprocess_proto:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700989
990loop.subprocess_exec() and SubprocessProtocol
991---------------------------------------------
992
Carol Willingc9d66f02018-09-14 10:06:55 -0700993An example of a subprocess protocol used to get the output of a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700994subprocess and to wait for the subprocess exit.
995
marload6fc732a2020-07-11 00:43:31 +0900996The subprocess is created by the :meth:`loop.subprocess_exec` method::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700997
998 import asyncio
999 import sys
1000
1001 class DateProtocol(asyncio.SubprocessProtocol):
1002 def __init__(self, exit_future):
1003 self.exit_future = exit_future
1004 self.output = bytearray()
1005
1006 def pipe_data_received(self, fd, data):
1007 self.output.extend(data)
1008
1009 def process_exited(self):
1010 self.exit_future.set_result(True)
1011
1012 async def get_date():
1013 # Get a reference to the event loop as we plan to use
1014 # low-level APIs.
1015 loop = asyncio.get_running_loop()
1016
1017 code = 'import datetime; print(datetime.datetime.now())'
1018 exit_future = asyncio.Future(loop=loop)
1019
1020 # Create the subprocess controlled by DateProtocol;
1021 # redirect the standard output into a pipe.
1022 transport, protocol = await loop.subprocess_exec(
1023 lambda: DateProtocol(exit_future),
1024 sys.executable, '-c', code,
1025 stdin=None, stderr=None)
1026
1027 # Wait for the subprocess exit using the process_exited()
1028 # method of the protocol.
1029 await exit_future
1030
1031 # Close the stdout pipe.
1032 transport.close()
1033
1034 # Read the output which was collected by the
1035 # pipe_data_received() method of the protocol.
1036 data = bytes(protocol.output)
1037 return data.decode('ascii').rstrip()
1038
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001039 date = asyncio.run(get_date())
1040 print(f"Current date: {date}")
Yury Selivanov394374e2018-09-17 15:35:24 -04001041
1042See also the :ref:`same example <asyncio_example_create_subprocess_exec>`
1043written using high-level APIs.