blob: f08738dd62bb5cc31c60ec9d1b63c64dbc9f9617 [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
Guido van Rossum589872c2014-03-29 21:14:04 -070072Transports are classes provided by :mod:`asyncio` in order to abstract
Yury Selivanov7c7605f2018-09-11 09:54:40 -070073various kinds of communication channels.
Victor Stinnerea3183f2013-12-03 01:08:00 +010074
Yury Selivanov7c7605f2018-09-11 09:54:40 -070075Transport objects are always instantiated by an
Pablo Galindo5033e312019-02-10 00:21:37 +000076:ref:`asyncio event loop <asyncio-event-loop>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010077
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078asyncio implements transports for TCP, UDP, SSL, and subprocess pipes.
79The methods available on a transport depend on the transport's kind.
Victor Stinnerea3183f2013-12-03 01:08:00 +010080
Victor Stinner83704962015-02-25 14:24:15 +010081The transport classes are :ref:`not thread safe <asyncio-multithreading>`.
82
Yury Selivanov3432f2f2016-12-12 16:44:58 -050083
Yury Selivanov7c7605f2018-09-11 09:54:40 -070084Transports Hierarchy
85--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010086
87.. class:: BaseTransport
88
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089 Base class for all transports. Contains methods that all
90 asyncio transports share.
Victor Stinnerea3183f2013-12-03 01:08:00 +010091
Yury Selivanov7c7605f2018-09-11 09:54:40 -070092.. class:: WriteTransport(BaseTransport)
Victor Stinnerea3183f2013-12-03 01:08:00 +010093
Yury Selivanov7c7605f2018-09-11 09:54:40 -070094 A base transport for write-only connections.
Victor Stinnerea3183f2013-12-03 01:08:00 +010095
Yury Selivanov7c7605f2018-09-11 09:54:40 -070096 Instances of the *WriteTransport* class are returned from
97 the :meth:`loop.connect_write_pipe` event loop method and
98 are also used by subprocess-related methods like
99 :meth:`loop.subprocess_exec`.
Yury Selivanov1744d532015-11-16 12:46:41 -0500100
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700101.. class:: ReadTransport(BaseTransport)
Yury Selivanov1744d532015-11-16 12:46:41 -0500102
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700103 A base transport for read-only connections.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100104
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700105 Instances of the *ReadTransport* class are returned from
106 the :meth:`loop.connect_read_pipe` event loop method and
107 are also used by subprocess-related methods like
108 :meth:`loop.subprocess_exec`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100109
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700110.. class:: Transport(WriteTransport, ReadTransport)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100111
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700112 Interface representing a bidirectional transport, such as a
113 TCP connection.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100114
Carol Willingc9d66f02018-09-14 10:06:55 -0700115 The user does not instantiate a transport directly; they call a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700116 utility function, passing it a protocol factory and other
117 information necessary to create the transport and protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100118
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700119 Instances of the *Transport* class are returned from or used by
120 event loop methods like :meth:`loop.create_connection`,
121 :meth:`loop.create_unix_connection`,
122 :meth:`loop.create_server`, :meth:`loop.sendfile`, etc.
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200123
Victor Stinnerea3183f2013-12-03 01:08:00 +0100124
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700125.. class:: DatagramTransport(BaseTransport)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100126
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700127 A transport for datagram (UDP) connections.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700129 Instances of the *DatagramTransport* class are returned from
130 the :meth:`loop.create_datagram_endpoint` event loop method.
Yury Selivanovd757aaf2017-12-18 17:03:23 -0500131
Victor Stinnerea3183f2013-12-03 01:08:00 +0100132
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700133.. class:: SubprocessTransport(BaseTransport)
134
135 An abstraction to represent a connection between a parent and its
136 child OS process.
137
138 Instances of the *SubprocessTransport* class are returned from
139 event loop methods :meth:`loop.subprocess_shell` and
140 :meth:`loop.subprocess_exec`.
141
142
143Base Transport
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100144--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100145
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700146.. method:: BaseTransport.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100147
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700148 Close the transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100149
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700150 If the transport has a buffer for outgoing
151 data, buffered data will be flushed asynchronously. No more data
152 will be received. After all buffered data is flushed, the
153 protocol's :meth:`protocol.connection_lost()
154 <BaseProtocol.connection_lost>` method will be called with
155 :const:`None` as its argument.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100156
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700157.. method:: BaseTransport.is_closing()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100158
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700159 Return ``True`` if the transport is closing or is closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100160
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700161.. method:: BaseTransport.get_extra_info(name, default=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100162
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700163 Return information about the transport or underlying resources
164 it uses.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100165
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700166 *name* is a string representing the piece of transport-specific
167 information to get.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700169 *default* is the value to return if the information is not
170 available, or if the transport does not support querying it
171 with the given third-party event loop implementation or on the
172 current platform.
Victor Stinner52bb9492014-08-26 00:22:28 +0200173
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700174 For example, the following code attempts to get the underlying
175 socket object of the transport::
Victor Stinner52bb9492014-08-26 00:22:28 +0200176
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700177 sock = transport.get_extra_info('socket')
178 if sock is not None:
179 print(sock.getsockopt(...))
Victor Stinner52bb9492014-08-26 00:22:28 +0200180
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700181 Categories of information that can be queried on some transports:
Victor Stinner52bb9492014-08-26 00:22:28 +0200182
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700183 * socket:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100184
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700185 - ``'peername'``: the remote address to which the socket is
186 connected, result of :meth:`socket.socket.getpeername`
187 (``None`` on error)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100188
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700189 - ``'socket'``: :class:`socket.socket` instance
Victor Stinnerea3183f2013-12-03 01:08:00 +0100190
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700191 - ``'sockname'``: the socket's own address,
192 result of :meth:`socket.socket.getsockname`
Kojo Idrissa5200a7c2017-06-20 14:32:00 -0500193
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700194 * SSL socket:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100195
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700196 - ``'compression'``: the compression algorithm being used as a
197 string, or ``None`` if the connection isn't compressed; result
198 of :meth:`ssl.SSLSocket.compression`
Victor Stinner52bb9492014-08-26 00:22:28 +0200199
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700200 - ``'cipher'``: a three-value tuple containing the name of the
201 cipher being used, the version of the SSL protocol that defines
202 its use, and the number of secret bits being used; result of
203 :meth:`ssl.SSLSocket.cipher`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100204
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700205 - ``'peercert'``: peer certificate; result of
206 :meth:`ssl.SSLSocket.getpeercert`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100207
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700208 - ``'sslcontext'``: :class:`ssl.SSLContext` instance
Victor Stinnerea3183f2013-12-03 01:08:00 +0100209
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700210 - ``'ssl_object'``: :class:`ssl.SSLObject` or
211 :class:`ssl.SSLSocket` instance
Victor Stinnerea3183f2013-12-03 01:08:00 +0100212
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700213 * pipe:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100214
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700215 - ``'pipe'``: pipe object
Victor Stinnerea3183f2013-12-03 01:08:00 +0100216
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700217 * subprocess:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700219 - ``'subprocess'``: :class:`subprocess.Popen` instance
220
221.. method:: BaseTransport.set_protocol(protocol)
222
223 Set a new protocol.
224
225 Switching protocol should only be done when both
226 protocols are documented to support the switch.
227
228.. method:: BaseTransport.get_protocol()
229
230 Return the current protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100231
232
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700233Read-only Transports
234--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100235
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700236.. method:: ReadTransport.is_reading()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100237
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700238 Return ``True`` if the transport is receiving new data.
239
240 .. versionadded:: 3.7
241
242.. method:: ReadTransport.pause_reading()
243
244 Pause the receiving end of the transport. No data will be passed to
245 the protocol's :meth:`protocol.data_received() <Protocol.data_received>`
246 method until :meth:`resume_reading` is called.
247
248 .. versionchanged:: 3.7
249 The method is idempotent, i.e. it can be called when the
250 transport is already paused or closed.
251
252.. method:: ReadTransport.resume_reading()
253
254 Resume the receiving end. The protocol's
255 :meth:`protocol.data_received() <Protocol.data_received>` method
256 will be called once again if some data is available for reading.
257
258 .. versionchanged:: 3.7
259 The method is idempotent, i.e. it can be called when the
260 transport is already reading.
261
262
263Write-only Transports
264---------------------
265
266.. method:: WriteTransport.abort()
267
268 Close the transport immediately, without waiting for pending operations
269 to complete. Buffered data will be lost. No more data will be received.
270 The protocol's :meth:`protocol.connection_lost()
271 <BaseProtocol.connection_lost>` method will eventually be
272 called with :const:`None` as its argument.
273
274.. method:: WriteTransport.can_write_eof()
275
276 Return :const:`True` if the transport supports
277 :meth:`~WriteTransport.write_eof`, :const:`False` if not.
278
279.. method:: WriteTransport.get_write_buffer_size()
280
281 Return the current size of the output buffer used by the transport.
282
283.. method:: WriteTransport.get_write_buffer_limits()
284
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400285 Get the *high* and *low* watermarks for write flow control. Return a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700286 tuple ``(low, high)`` where *low* and *high* are positive number of
287 bytes.
288
289 Use :meth:`set_write_buffer_limits` to set the limits.
290
291 .. versionadded:: 3.4.2
292
293.. method:: WriteTransport.set_write_buffer_limits(high=None, low=None)
294
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400295 Set the *high* and *low* watermarks for write flow control.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700296
297 These two values (measured in number of
298 bytes) control when the protocol's
299 :meth:`protocol.pause_writing() <BaseProtocol.pause_writing>`
300 and :meth:`protocol.resume_writing() <BaseProtocol.resume_writing>`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400301 methods are called. If specified, the low watermark must be less
302 than or equal to the high watermark. Neither *high* nor *low*
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700303 can be negative.
304
305 :meth:`~BaseProtocol.pause_writing` is called when the buffer size
306 becomes greater than or equal to the *high* value. If writing has
307 been paused, :meth:`~BaseProtocol.resume_writing` is called when
308 the buffer size becomes less than or equal to the *low* value.
309
310 The defaults are implementation-specific. If only the
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400311 high watermark is given, the low watermark defaults to an
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700312 implementation-specific value less than or equal to the
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400313 high watermark. Setting *high* to zero forces *low* to zero as
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700314 well, and causes :meth:`~BaseProtocol.pause_writing` to be called
315 whenever the buffer becomes non-empty. Setting *low* to zero causes
316 :meth:`~BaseProtocol.resume_writing` to be called only once the
317 buffer is empty. Use of zero for either limit is generally
318 sub-optimal as it reduces opportunities for doing I/O and
319 computation concurrently.
320
321 Use :meth:`~WriteTransport.get_write_buffer_limits`
322 to get the limits.
323
324.. method:: WriteTransport.write(data)
325
326 Write some *data* bytes to the transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100327
328 This method does not block; it buffers the data and arranges for it
329 to be sent out asynchronously.
330
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700331.. method:: WriteTransport.writelines(list_of_data)
332
333 Write a list (or any iterable) of data bytes to the transport.
334 This is functionally equivalent to calling :meth:`write` on each
335 element yielded by the iterable, but may be implemented more
336 efficiently.
337
338.. method:: WriteTransport.write_eof()
339
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400340 Close the write end of the transport after flushing all buffered data.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700341 Data may still be received.
342
343 This method can raise :exc:`NotImplementedError` if the transport
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400344 (e.g. SSL) doesn't support half-closed connections.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700345
346
347Datagram Transports
348-------------------
349
350.. method:: DatagramTransport.sendto(data, addr=None)
351
352 Send the *data* bytes to the remote peer given by *addr* (a
353 transport-dependent target address). If *addr* is :const:`None`,
354 the data is sent to the target address given on transport
355 creation.
356
357 This method does not block; it buffers the data and arranges
358 for it to be sent out asynchronously.
359
Victor Stinnerea3183f2013-12-03 01:08:00 +0100360.. method:: DatagramTransport.abort()
361
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700362 Close the transport immediately, without waiting for pending
363 operations to complete. Buffered data will be lost.
364 No more data will be received. The protocol's
365 :meth:`protocol.connection_lost() <BaseProtocol.connection_lost>`
366 method will eventually be called with :const:`None` as its argument.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
368
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700369.. _asyncio-subprocess-transports:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100370
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700371Subprocess Transports
372---------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100373
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700374.. method:: SubprocessTransport.get_pid()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100375
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700376 Return the subprocess process id as an integer.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100377
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700378.. method:: SubprocessTransport.get_pipe_transport(fd)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100379
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700380 Return the transport for the communication pipe corresponding to the
381 integer file descriptor *fd*:
Victor Stinner4270a242014-10-13 23:56:43 +0200382
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700383 * ``0``: readable streaming transport of the standard input (*stdin*),
384 or :const:`None` if the subprocess was not created with ``stdin=PIPE``
385 * ``1``: writable streaming transport of the standard output (*stdout*),
386 or :const:`None` if the subprocess was not created with ``stdout=PIPE``
387 * ``2``: writable streaming transport of the standard error (*stderr*),
388 or :const:`None` if the subprocess was not created with ``stderr=PIPE``
389 * other *fd*: :const:`None`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100390
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700391.. method:: SubprocessTransport.get_returncode()
Victor Stinner933a8c82013-12-03 01:59:38 +0100392
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700393 Return the subprocess return code as an integer or :const:`None`
Carol Willingc9d66f02018-09-14 10:06:55 -0700394 if it hasn't returned, which is similar to the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700395 :attr:`subprocess.Popen.returncode` attribute.
Victor Stinner933a8c82013-12-03 01:59:38 +0100396
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700397.. method:: SubprocessTransport.kill()
Victor Stinner933a8c82013-12-03 01:59:38 +0100398
Yury Selivanov3faaa882018-09-14 13:32:07 -0700399 Kill the subprocess.
Victor Stinner933a8c82013-12-03 01:59:38 +0100400
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700401 On POSIX systems, the function sends SIGKILL to the subprocess.
402 On Windows, this method is an alias for :meth:`terminate`.
Victor Stinner933a8c82013-12-03 01:59:38 +0100403
Yury Selivanov3faaa882018-09-14 13:32:07 -0700404 See also :meth:`subprocess.Popen.kill`.
405
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700406.. method:: SubprocessTransport.send_signal(signal)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100407
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700408 Send the *signal* number to the subprocess, as in
409 :meth:`subprocess.Popen.send_signal`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100410
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700411.. method:: SubprocessTransport.terminate()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100412
Yury Selivanov3faaa882018-09-14 13:32:07 -0700413 Stop the subprocess.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100414
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700415 On POSIX systems, this method sends SIGTERM to the subprocess.
416 On Windows, the Windows API function TerminateProcess() is called to
417 stop the subprocess.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100418
Yury Selivanov3faaa882018-09-14 13:32:07 -0700419 See also :meth:`subprocess.Popen.terminate`.
420
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700421.. method:: SubprocessTransport.close()
Victor Stinner4270a242014-10-13 23:56:43 +0200422
Yury Selivanov3faaa882018-09-14 13:32:07 -0700423 Kill the subprocess by calling the :meth:`kill` method.
424
425 If the subprocess hasn't returned yet, and close transports of
426 *stdin*, *stdout*, and *stderr* pipes.
Victor Stinner4270a242014-10-13 23:56:43 +0200427
Victor Stinnerea3183f2013-12-03 01:08:00 +0100428
Victor Stinner9592edb2014-02-02 15:03:02 +0100429.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100430
431Protocols
432=========
433
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700434asyncio provides a set of abstract base classes that should be used
435to implement network protocols. Those classes are meant to be used
436together with :ref:`transports <asyncio-transport>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
Carol Willingc9d66f02018-09-14 10:06:55 -0700438Subclasses of abstract base protocol classes may implement some or
439all methods. All these methods are callbacks: they are called by
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700440transports on certain events, for example when some data is received.
Carol Willingc9d66f02018-09-14 10:06:55 -0700441A base protocol method should be called by the corresponding transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100442
443
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700444Base Protocols
445--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100446
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700447.. class:: BaseProtocol
Victor Stinnerea3183f2013-12-03 01:08:00 +0100448
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700449 Base protocol with methods that all protocols share.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700451.. class:: Protocol(BaseProtocol)
452
453 The base class for implementing streaming protocols
454 (TCP, Unix sockets, etc).
455
456.. class:: BufferedProtocol(BaseProtocol)
Yury Selivanov631fd382018-01-28 16:30:26 -0500457
458 A base class for implementing streaming protocols with manual
459 control of the receive buffer.
460
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700461.. class:: DatagramProtocol(BaseProtocol)
Yury Selivanov631fd382018-01-28 16:30:26 -0500462
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700463 The base class for implementing datagram (UDP) protocols.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700465.. class:: SubprocessProtocol(BaseProtocol)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100466
467 The base class for implementing protocols communicating with child
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700468 processes (unidirectional pipes).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100469
470
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700471Base Protocol
472-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700474All asyncio protocols can implement Base Protocol callbacks.
475
476.. rubric:: Connection Callbacks
477
478Connection callbacks are called on all protocols, exactly once per
479a successful connection. All other protocol callbacks can only be
480called between those two methods.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100481
482.. method:: BaseProtocol.connection_made(transport)
483
484 Called when a connection is made.
485
486 The *transport* argument is the transport representing the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700487 connection. The protocol is responsible for storing the reference
488 to its transport.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100489
490.. method:: BaseProtocol.connection_lost(exc)
491
492 Called when the connection is lost or closed.
493
494 The argument is either an exception object or :const:`None`.
495 The latter means a regular EOF is received, or the connection was
496 aborted or closed by this side of the connection.
497
Victor Stinnerea3183f2013-12-03 01:08:00 +0100498
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700499.. rubric:: Flow Control Callbacks
Victor Stinnerea3183f2013-12-03 01:08:00 +0100500
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700501Flow control callbacks can be called by transports to pause or
502resume writing performed by the protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100503
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700504See the documentation of the :meth:`~WriteTransport.set_write_buffer_limits`
505method for more details.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100506
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700507.. method:: BaseProtocol.pause_writing()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100508
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400509 Called when the transport's buffer goes over the high watermark.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100510
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700511.. method:: BaseProtocol.resume_writing()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100512
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400513 Called when the transport's buffer drains below the low watermark.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700514
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400515If the buffer size equals the high watermark,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700516:meth:`~BaseProtocol.pause_writing` is not called: the buffer size must
517go strictly over.
518
519Conversely, :meth:`~BaseProtocol.resume_writing` is called when the
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400520buffer size is equal or lower than the low watermark. These end
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700521conditions are important to ensure that things go as expected when
522either mark is zero.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100523
524
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700525Streaming Protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100526-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700528Event methods, such as :meth:`loop.create_server`,
529:meth:`loop.create_unix_server`, :meth:`loop.create_connection`,
530:meth:`loop.create_unix_connection`, :meth:`loop.connect_accepted_socket`,
531:meth:`loop.connect_read_pipe`, and :meth:`loop.connect_write_pipe`
532accept factories that return streaming protocols.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100533
534.. method:: Protocol.data_received(data)
535
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700536 Called when some data is received. *data* is a non-empty bytes
537 object containing the incoming data.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100538
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700539 Whether the data is buffered, chunked or reassembled depends on
540 the transport. In general, you shouldn't rely on specific semantics
Carol Willingc9d66f02018-09-14 10:06:55 -0700541 and instead make your parsing generic and flexible. However,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700542 data is always received in the correct order.
543
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400544 The method can be called an arbitrary number of times while
545 a connection is open.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700546
547 However, :meth:`protocol.eof_received() <Protocol.eof_received>`
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400548 is called at most once. Once `eof_received()` is called,
549 ``data_received()`` is not called anymore.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100550
551.. method:: Protocol.eof_received()
552
Barry Warsawdd9a0a12017-04-07 14:18:14 -0400553 Called when the other end signals it won't send any more data
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700554 (for example by calling :meth:`transport.write_eof()
555 <WriteTransport.write_eof>`, if the other end also uses
Victor Stinnerea3183f2013-12-03 01:08:00 +0100556 asyncio).
557
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300558 This method may return a false value (including ``None``), in which case
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559 the transport will close itself. Conversely, if this method returns a
Carol Willingc9d66f02018-09-14 10:06:55 -0700560 true value, the protocol used determines whether to close the transport.
561 Since the default implementation returns ``None``, it implicitly closes the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700562 connection.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100563
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400564 Some transports, including SSL, don't support half-closed connections,
565 in which case returning true from this method will result in the connection
566 being closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100567
Victor Stinnerea3183f2013-12-03 01:08:00 +0100568
Victor Stinner54a231d2015-01-29 13:33:15 +0100569State machine:
570
Yury Selivanov631fd382018-01-28 16:30:26 -0500571.. code-block:: none
572
573 start -> connection_made
574 [-> data_received]*
575 [-> eof_received]?
576 -> connection_lost -> end
577
578
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700579Buffered Streaming Protocols
580----------------------------
Yury Selivanov631fd382018-01-28 16:30:26 -0500581
582.. versionadded:: 3.7
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700583 **Important:** this has been added to asyncio in Python 3.7
584 *on a provisional basis*! This is as an experimental API that
585 might be changed or removed completely in Python 3.8.
Yury Selivanov631fd382018-01-28 16:30:26 -0500586
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700587Buffered Protocols can be used with any event loop method
588that supports `Streaming Protocols`_.
Yury Selivanov631fd382018-01-28 16:30:26 -0500589
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400590``BufferedProtocol`` implementations allow explicit manual allocation
Carol Willingc9d66f02018-09-14 10:06:55 -0700591and control of the receive buffer. Event loops can then use the buffer
Yury Selivanov631fd382018-01-28 16:30:26 -0500592provided by the protocol to avoid unnecessary data copies. This
593can result in noticeable performance improvement for protocols that
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400594receive big amounts of data. Sophisticated protocol implementations
595can significantly reduce the number of buffer allocations.
Yury Selivanov631fd382018-01-28 16:30:26 -0500596
597The following callbacks are called on :class:`BufferedProtocol`
598instances:
599
Yury Selivanovdbf10222018-05-28 14:31:28 -0400600.. method:: BufferedProtocol.get_buffer(sizehint)
Yury Selivanov631fd382018-01-28 16:30:26 -0500601
Yury Selivanovdbf10222018-05-28 14:31:28 -0400602 Called to allocate a new receive buffer.
603
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400604 *sizehint* is the recommended minimum size for the returned
605 buffer. It is acceptable to return smaller or larger buffers
Yury Selivanovdbf10222018-05-28 14:31:28 -0400606 than what *sizehint* suggests. When set to -1, the buffer size
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400607 can be arbitrary. It is an error to return a buffer with a zero size.
Yury Selivanovdbf10222018-05-28 14:31:28 -0400608
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400609 ``get_buffer()`` must return an object implementing the
Yury Selivanovdbf10222018-05-28 14:31:28 -0400610 :ref:`buffer protocol <bufferobjects>`.
Yury Selivanov631fd382018-01-28 16:30:26 -0500611
612.. method:: BufferedProtocol.buffer_updated(nbytes)
613
614 Called when the buffer was updated with the received data.
615
616 *nbytes* is the total number of bytes that were written to the buffer.
617
618.. method:: BufferedProtocol.eof_received()
619
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700620 See the documentation of the :meth:`protocol.eof_received()
621 <Protocol.eof_received>` method.
Yury Selivanov631fd382018-01-28 16:30:26 -0500622
623
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700624:meth:`~BufferedProtocol.get_buffer` can be called an arbitrary number
625of times during a connection. However, :meth:`protocol.eof_received()
626<Protocol.eof_received>` is called at most once
627and, if called, :meth:`~BufferedProtocol.get_buffer` and
628:meth:`~BufferedProtocol.buffer_updated` won't be called after it.
Yury Selivanov631fd382018-01-28 16:30:26 -0500629
630State machine:
631
632.. code-block:: none
633
634 start -> connection_made
635 [-> get_buffer
636 [-> buffer_updated]?
637 ]*
638 [-> eof_received]?
639 -> connection_lost -> end
Victor Stinner54a231d2015-01-29 13:33:15 +0100640
641
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700642Datagram Protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100643------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100644
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700645Datagram Protocol instances should be constructed by protocol
646factories passed to the :meth:`loop.create_datagram_endpoint` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100647
648.. method:: DatagramProtocol.datagram_received(data, addr)
649
650 Called when a datagram is received. *data* is a bytes object containing
651 the incoming data. *addr* is the address of the peer sending the data;
652 the exact format depends on the transport.
653
654.. method:: DatagramProtocol.error_received(exc)
655
656 Called when a previous send or receive operation raises an
657 :class:`OSError`. *exc* is the :class:`OSError` instance.
658
659 This method is called in rare conditions, when the transport (e.g. UDP)
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400660 detects that a datagram could not be delivered to its recipient.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100661 In many conditions though, undeliverable datagrams will be silently
662 dropped.
663
Victor Stinnerea3183f2013-12-03 01:08:00 +0100664.. note::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100665
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700666 On BSD systems (macOS, FreeBSD, etc.) flow control is not supported
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400667 for datagram protocols, because there is no reliable way to detect send
Carol Willingc9d66f02018-09-14 10:06:55 -0700668 failures caused by writing too many packets.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700669
Carol Willingc9d66f02018-09-14 10:06:55 -0700670 The socket always appears 'ready' and excess packets are dropped. An
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700671 :class:`OSError` with ``errno`` set to :const:`errno.ENOBUFS` may
672 or may not be raised; if it is raised, it will be reported to
Larry Hastings3732ed22014-03-15 21:13:56 -0700673 :meth:`DatagramProtocol.error_received` but otherwise ignored.
674
Victor Stinnerea3183f2013-12-03 01:08:00 +0100675
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700676.. _asyncio-subprocess-protocols:
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100677
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700678Subprocess Protocols
679--------------------
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100680
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700681Datagram Protocol instances should be constructed by protocol
682factories passed to the :meth:`loop.subprocess_exec` and
683:meth:`loop.subprocess_shell` methods.
684
685.. method:: SubprocessProtocol.pipe_data_received(fd, data)
686
687 Called when the child process writes data into its stdout or stderr
688 pipe.
689
690 *fd* is the integer file descriptor of the pipe.
691
692 *data* is a non-empty bytes object containing the received data.
693
694.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
695
696 Called when one of the pipes communicating with the child process
697 is closed.
698
699 *fd* is the integer file descriptor that was closed.
700
701.. method:: SubprocessProtocol.process_exited()
702
703 Called when the child process has exited.
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100704
705
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700706Examples
707========
Victor Stinnered051592014-10-12 20:18:16 +0200708
Yury Selivanov394374e2018-09-17 15:35:24 -0400709.. _asyncio_example_tcp_echo_server_protocol:
Victor Stinnered051592014-10-12 20:18:16 +0200710
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700711TCP Echo Server
712---------------
Victor Stinnered051592014-10-12 20:18:16 +0200713
Carol Willingc9d66f02018-09-14 10:06:55 -0700714Create a TCP echo server using the :meth:`loop.create_server` method, send back
715received data, and close the connection::
Victor Stinnera881a7f2013-12-09 13:19:23 +0100716
717 import asyncio
718
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700719
Braden Groom43a5bd72018-10-15 14:39:16 -0700720 class EchoServerProtocol(asyncio.Protocol):
Victor Stinnera881a7f2013-12-09 13:19:23 +0100721 def connection_made(self, transport):
722 peername = transport.get_extra_info('peername')
Victor Stinnerc2721b42014-10-12 11:13:40 +0200723 print('Connection from {}'.format(peername))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100724 self.transport = transport
725
726 def data_received(self, data):
Victor Stinnerc2721b42014-10-12 11:13:40 +0200727 message = data.decode()
728 print('Data received: {!r}'.format(message))
729
730 print('Send: {!r}'.format(message))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100731 self.transport.write(data)
732
Victor Stinner53664342014-10-12 11:35:09 +0200733 print('Close the client socket')
Victor Stinnera881a7f2013-12-09 13:19:23 +0100734 self.transport.close()
735
Victor Stinnera881a7f2013-12-09 13:19:23 +0100736
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700737 async def main():
738 # Get a reference to the event loop as we plan to use
739 # low-level APIs.
740 loop = asyncio.get_running_loop()
Victor Stinnerc2721b42014-10-12 11:13:40 +0200741
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700742 server = await loop.create_server(
Braden Groom43a5bd72018-10-15 14:39:16 -0700743 lambda: EchoServerProtocol(),
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700744 '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100745
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700746 async with server:
747 await server.serve_forever()
748
749
750 asyncio.run(main())
751
Victor Stinnera881a7f2013-12-09 13:19:23 +0100752
Victor Stinnered051592014-10-12 20:18:16 +0200753.. seealso::
754
755 The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700756 example uses the high-level :func:`asyncio.start_server` function.
757
Yury Selivanov394374e2018-09-17 15:35:24 -0400758.. _asyncio_example_tcp_echo_client_protocol:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700759
760TCP Echo Client
761---------------
762
Carol Willingc9d66f02018-09-14 10:06:55 -0700763A TCP echo client using the :meth:`loop.create_connection` method, sends
764data, and waits until the connection is closed::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700765
766 import asyncio
767
768
769 class EchoClientProtocol(asyncio.Protocol):
770 def __init__(self, message, on_con_lost, loop):
771 self.message = message
772 self.loop = loop
773 self.on_con_lost = on_con_lost
774
775 def connection_made(self, transport):
776 transport.write(self.message.encode())
777 print('Data sent: {!r}'.format(self.message))
778
779 def data_received(self, data):
780 print('Data received: {!r}'.format(data.decode()))
781
782 def connection_lost(self, exc):
783 print('The server closed the connection')
784 self.on_con_lost.set_result(True)
785
786
787 async def main():
788 # Get a reference to the event loop as we plan to use
789 # low-level APIs.
790 loop = asyncio.get_running_loop()
791
792 on_con_lost = loop.create_future()
793 message = 'Hello World!'
794
795 transport, protocol = await loop.create_connection(
796 lambda: EchoClientProtocol(message, on_con_lost, loop),
797 '127.0.0.1', 8888)
798
799 # Wait until the protocol signals that the connection
800 # is lost and close the transport.
801 try:
802 await on_con_lost
803 finally:
804 transport.close()
805
806
807 asyncio.run(main())
808
809
810.. seealso::
811
812 The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
813 example uses the high-level :func:`asyncio.open_connection` function.
814
815
816.. _asyncio-udp-echo-server-protocol:
817
818UDP Echo Server
819---------------
820
Carol Willingc9d66f02018-09-14 10:06:55 -0700821A UDP echo server, using the :meth:`loop.create_datagram_endpoint`
822method, sends back received data::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700823
824 import asyncio
825
826
827 class EchoServerProtocol:
828 def connection_made(self, transport):
829 self.transport = transport
830
831 def datagram_received(self, data, addr):
832 message = data.decode()
833 print('Received %r from %s' % (message, addr))
834 print('Send %r to %s' % (message, addr))
835 self.transport.sendto(data, addr)
836
837
838 async def main():
839 print("Starting UDP server")
840
841 # Get a reference to the event loop as we plan to use
842 # low-level APIs.
843 loop = asyncio.get_running_loop()
844
845 # One protocol instance will be created to serve all
846 # client requests.
847 transport, protocol = await loop.create_datagram_endpoint(
848 lambda: EchoServerProtocol(),
849 local_addr=('127.0.0.1', 9999))
850
851 try:
852 await asyncio.sleep(3600) # Serve for 1 hour.
853 finally:
854 transport.close()
855
856
857 asyncio.run(main())
Victor Stinnered051592014-10-12 20:18:16 +0200858
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200859
860.. _asyncio-udp-echo-client-protocol:
861
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700862UDP Echo Client
863---------------
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200864
Carol Willingc9d66f02018-09-14 10:06:55 -0700865A UDP echo client, using the :meth:`loop.create_datagram_endpoint`
866method, sends data and closes the transport when it receives the answer::
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200867
868 import asyncio
869
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700870
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200871 class EchoClientProtocol:
872 def __init__(self, message, loop):
873 self.message = message
874 self.loop = loop
875 self.transport = None
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700876 self.on_con_lost = loop.create_future()
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200877
878 def connection_made(self, transport):
879 self.transport = transport
880 print('Send:', self.message)
881 self.transport.sendto(self.message.encode())
882
883 def datagram_received(self, data, addr):
884 print("Received:", data.decode())
885
886 print("Close the socket")
887 self.transport.close()
888
889 def error_received(self, exc):
890 print('Error received:', exc)
891
892 def connection_lost(self, exc):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700893 print("Connection closed")
894 self.on_con_lost.set_result(True)
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200895
896
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700897 async def main():
898 # Get a reference to the event loop as we plan to use
899 # low-level APIs.
900 loop = asyncio.get_running_loop()
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200901
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700902 message = "Hello World!"
903 transport, protocol = await loop.create_datagram_endpoint(
904 lambda: EchoClientProtocol(message, loop),
905 remote_addr=('127.0.0.1', 9999))
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200906
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700907 try:
908 await protocol.on_con_lost
909 finally:
910 transport.close()
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200911
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200912
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700913 asyncio.run(main())
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200914
915
Yury Selivanov394374e2018-09-17 15:35:24 -0400916.. _asyncio_example_create_connection:
Victor Stinnera881a7f2013-12-09 13:19:23 +0100917
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700918Connecting Existing Sockets
919---------------------------
Victor Stinner04e6df32014-10-11 16:16:27 +0200920
921Wait until a socket receives data using the
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700922:meth:`loop.create_connection` method with a protocol::
Victor Stinner04e6df32014-10-11 16:16:27 +0200923
924 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700925 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200926
Victor Stinner04e6df32014-10-11 16:16:27 +0200927
928 class MyProtocol(asyncio.Protocol):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700929
930 def __init__(self, loop):
931 self.transport = None
932 self.on_con_lost = loop.create_future()
Victor Stinner04e6df32014-10-11 16:16:27 +0200933
934 def connection_made(self, transport):
935 self.transport = transport
936
937 def data_received(self, data):
938 print("Received:", data.decode())
939
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700940 # We are done: close the transport;
941 # connection_lost() will be called automatically.
Victor Stinner04e6df32014-10-11 16:16:27 +0200942 self.transport.close()
943
944 def connection_lost(self, exc):
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700945 # The socket has been closed
946 self.on_con_lost.set_result(True)
Victor Stinner04e6df32014-10-11 16:16:27 +0200947
Victor Stinner04e6df32014-10-11 16:16:27 +0200948
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700949 async def main():
950 # Get a reference to the event loop as we plan to use
951 # low-level APIs.
952 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200953
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700954 # Create a pair of connected sockets
955 rsock, wsock = socket.socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200956
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700957 # Register the socket to wait for data.
958 transport, protocol = await loop.create_connection(
959 lambda: MyProtocol(loop), sock=rsock)
960
961 # Simulate the reception of data from the network.
962 loop.call_soon(wsock.send, 'abc'.encode())
963
964 try:
965 await protocol.on_con_lost
966 finally:
967 transport.close()
968 wsock.close()
969
970 asyncio.run(main())
Victor Stinner04e6df32014-10-11 16:16:27 +0200971
972.. seealso::
973
974 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400975 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700976 :meth:`loop.add_reader` method to register an FD.
Victor Stinner04e6df32014-10-11 16:16:27 +0200977
978 The :ref:`register an open socket to wait for data using streams
Yury Selivanov394374e2018-09-17 15:35:24 -0400979 <asyncio_example_create_connection-streams>` example uses high-level streams
Victor Stinner04e6df32014-10-11 16:16:27 +0200980 created by the :func:`open_connection` function in a coroutine.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700981
Yury Selivanov394374e2018-09-17 15:35:24 -0400982.. _asyncio_example_subprocess_proto:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700983
984loop.subprocess_exec() and SubprocessProtocol
985---------------------------------------------
986
Carol Willingc9d66f02018-09-14 10:06:55 -0700987An example of a subprocess protocol used to get the output of a
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700988subprocess and to wait for the subprocess exit.
989
990The subprocess is created by th :meth:`loop.subprocess_exec` method::
991
992 import asyncio
993 import sys
994
995 class DateProtocol(asyncio.SubprocessProtocol):
996 def __init__(self, exit_future):
997 self.exit_future = exit_future
998 self.output = bytearray()
999
1000 def pipe_data_received(self, fd, data):
1001 self.output.extend(data)
1002
1003 def process_exited(self):
1004 self.exit_future.set_result(True)
1005
1006 async def get_date():
1007 # Get a reference to the event loop as we plan to use
1008 # low-level APIs.
1009 loop = asyncio.get_running_loop()
1010
1011 code = 'import datetime; print(datetime.datetime.now())'
1012 exit_future = asyncio.Future(loop=loop)
1013
1014 # Create the subprocess controlled by DateProtocol;
1015 # redirect the standard output into a pipe.
1016 transport, protocol = await loop.subprocess_exec(
1017 lambda: DateProtocol(exit_future),
1018 sys.executable, '-c', code,
1019 stdin=None, stderr=None)
1020
1021 # Wait for the subprocess exit using the process_exited()
1022 # method of the protocol.
1023 await exit_future
1024
1025 # Close the stdout pipe.
1026 transport.close()
1027
1028 # Read the output which was collected by the
1029 # pipe_data_received() method of the protocol.
1030 data = bytes(protocol.output)
1031 return data.decode('ascii').rstrip()
1032
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001033 date = asyncio.run(get_date())
1034 print(f"Current date: {date}")
Yury Selivanov394374e2018-09-17 15:35:24 -04001035
1036See also the :ref:`same example <asyncio_example_create_subprocess_exec>`
1037written using high-level APIs.