R David Murray | 6a14381 | 2013-12-20 14:37:39 -0500 | [diff] [blame] | 1 | .. currentmodule:: asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 2 | |
lf | 627d2c8 | 2017-07-25 17:03:51 -0600 | [diff] [blame] | 3 | +++++++++++++++++++++++++++++++++++++++++++++ |
| 4 | Transports and protocols (callback based API) |
| 5 | +++++++++++++++++++++++++++++++++++++++++++++ |
| 6 | |
| 7 | **Source code:** :source:`Lib/asyncio/transports.py` |
| 8 | |
| 9 | **Source code:** :source:`Lib/asyncio/protocols.py` |
Victor Stinner | 1ca5ba6 | 2013-12-03 01:49:43 +0100 | [diff] [blame] | 10 | |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 11 | .. _asyncio-transport: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 12 | |
| 13 | Transports |
| 14 | ========== |
| 15 | |
Guido van Rossum | 589872c | 2014-03-29 21:14:04 -0700 | [diff] [blame] | 16 | Transports are classes provided by :mod:`asyncio` in order to abstract |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 17 | various kinds of communication channels. You generally won't instantiate |
Martin Panter | d210a70 | 2016-08-20 08:03:06 +0000 | [diff] [blame] | 18 | a transport yourself; instead, you will call an :class:`AbstractEventLoop` method |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 19 | which will create the transport and try to initiate the underlying |
| 20 | communication channel, calling you back when it succeeds. |
| 21 | |
| 22 | Once the communication channel is established, a transport is always |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 23 | paired with a :ref:`protocol <asyncio-protocol>` instance. The protocol can |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 24 | then call the transport's methods for various purposes. |
| 25 | |
| 26 | :mod:`asyncio` currently implements transports for TCP, UDP, SSL, and |
| 27 | subprocess pipes. The methods available on a transport depend on |
| 28 | the transport's kind. |
| 29 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 30 | The transport classes are :ref:`not thread safe <asyncio-multithreading>`. |
| 31 | |
Yury Selivanov | 3432f2f | 2016-12-12 16:44:58 -0500 | [diff] [blame] | 32 | .. versionchanged:: 3.6 |
| 33 | The socket option ``TCP_NODELAY`` is now set by default. |
| 34 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 35 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 36 | BaseTransport |
| 37 | ------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 38 | |
| 39 | .. class:: BaseTransport |
| 40 | |
| 41 | Base class for transports. |
| 42 | |
Mariatta | 091b84f | 2017-02-27 05:44:15 -0800 | [diff] [blame] | 43 | .. method:: close() |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 44 | |
| 45 | Close the transport. If the transport has a buffer for outgoing |
| 46 | data, buffered data will be flushed asynchronously. No more data |
| 47 | will be received. After all buffered data is flushed, the |
| 48 | protocol's :meth:`connection_lost` method will be called with |
| 49 | :const:`None` as its argument. |
| 50 | |
Mariatta | 091b84f | 2017-02-27 05:44:15 -0800 | [diff] [blame] | 51 | .. method:: is_closing() |
Yury Selivanov | 1744d53 | 2015-11-16 12:46:41 -0500 | [diff] [blame] | 52 | |
| 53 | Return ``True`` if the transport is closing or is closed. |
| 54 | |
Yury Selivanov | 344904c | 2015-11-16 12:47:15 -0500 | [diff] [blame] | 55 | .. versionadded:: 3.5.1 |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 56 | |
| 57 | .. method:: get_extra_info(name, default=None) |
| 58 | |
| 59 | Return optional transport information. *name* is a string representing |
| 60 | the piece of transport-specific information to get, *default* is the |
| 61 | value to return if the information doesn't exist. |
| 62 | |
| 63 | This method allows transport implementations to easily expose |
| 64 | channel-specific information. |
| 65 | |
| 66 | * socket: |
| 67 | |
| 68 | - ``'peername'``: the remote address to which the socket is connected, |
| 69 | result of :meth:`socket.socket.getpeername` (``None`` on error) |
| 70 | - ``'socket'``: :class:`socket.socket` instance |
| 71 | - ``'sockname'``: the socket's own address, |
| 72 | result of :meth:`socket.socket.getsockname` |
| 73 | |
| 74 | * SSL socket: |
| 75 | |
| 76 | - ``'compression'``: the compression algorithm being used as a string, |
| 77 | or ``None`` if the connection isn't compressed; result of |
| 78 | :meth:`ssl.SSLSocket.compression` |
| 79 | - ``'cipher'``: a three-value tuple containing the name of the cipher |
| 80 | being used, the version of the SSL protocol that defines its use, and |
| 81 | the number of secret bits being used; result of |
| 82 | :meth:`ssl.SSLSocket.cipher` |
| 83 | - ``'peercert'``: peer certificate; result of |
| 84 | :meth:`ssl.SSLSocket.getpeercert` |
| 85 | - ``'sslcontext'``: :class:`ssl.SSLContext` instance |
Victor Stinner | f7dc7fb | 2015-09-21 18:06:17 +0200 | [diff] [blame] | 86 | - ``'ssl_object'``: :class:`ssl.SSLObject` or :class:`ssl.SSLSocket` |
| 87 | instance |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 88 | |
| 89 | * pipe: |
| 90 | |
| 91 | - ``'pipe'``: pipe object |
| 92 | |
| 93 | * subprocess: |
| 94 | |
| 95 | - ``'subprocess'``: :class:`subprocess.Popen` instance |
| 96 | |
Berker Peksag | 2ebd6fe | 2016-11-07 23:36:14 +0300 | [diff] [blame] | 97 | .. method:: set_protocol(protocol) |
INADA Naoki | 1ea023e | 2016-11-04 16:33:47 +0900 | [diff] [blame] | 98 | |
| 99 | Set a new protocol. Switching protocol should only be done when both |
| 100 | protocols are documented to support the switch. |
| 101 | |
Berker Peksag | 2ebd6fe | 2016-11-07 23:36:14 +0300 | [diff] [blame] | 102 | .. versionadded:: 3.5.3 |
INADA Naoki | 1ea023e | 2016-11-04 16:33:47 +0900 | [diff] [blame] | 103 | |
Berker Peksag | 2ebd6fe | 2016-11-07 23:36:14 +0300 | [diff] [blame] | 104 | .. method:: get_protocol |
INADA Naoki | 1ea023e | 2016-11-04 16:33:47 +0900 | [diff] [blame] | 105 | |
| 106 | Return the current protocol. |
| 107 | |
Berker Peksag | 2ebd6fe | 2016-11-07 23:36:14 +0300 | [diff] [blame] | 108 | .. versionadded:: 3.5.3 |
INADA Naoki | 1ea023e | 2016-11-04 16:33:47 +0900 | [diff] [blame] | 109 | |
Victor Stinner | 04ce06b | 2015-09-21 18:27:52 +0200 | [diff] [blame] | 110 | .. versionchanged:: 3.5.1 |
Victor Stinner | f7dc7fb | 2015-09-21 18:06:17 +0200 | [diff] [blame] | 111 | ``'ssl_object'`` info was added to SSL sockets. |
| 112 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 113 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 114 | ReadTransport |
| 115 | ------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 116 | |
| 117 | .. class:: ReadTransport |
| 118 | |
| 119 | Interface for read-only transports. |
| 120 | |
Yury Selivanov | d757aaf | 2017-12-18 17:03:23 -0500 | [diff] [blame] | 121 | .. method:: is_reading() |
| 122 | |
| 123 | Return ``True`` if the transport is receiving new data. |
| 124 | |
| 125 | .. versionadded:: 3.7 |
| 126 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 127 | .. method:: pause_reading() |
| 128 | |
| 129 | Pause the receiving end of the transport. No data will be passed to |
Victor Stinner | 51f3129 | 2014-03-21 17:17:15 +0100 | [diff] [blame] | 130 | the protocol's :meth:`data_received` method until :meth:`resume_reading` |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 131 | is called. |
| 132 | |
Yury Selivanov | d757aaf | 2017-12-18 17:03:23 -0500 | [diff] [blame] | 133 | .. versionchanged:: 3.7 |
| 134 | The method is idempotent, i.e. it can be called when the |
| 135 | transport is already paused or closed. |
| 136 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 137 | .. method:: resume_reading() |
| 138 | |
| 139 | Resume the receiving end. The protocol's :meth:`data_received` method |
| 140 | will be called once again if some data is available for reading. |
| 141 | |
Yury Selivanov | d757aaf | 2017-12-18 17:03:23 -0500 | [diff] [blame] | 142 | .. versionchanged:: 3.7 |
| 143 | The method is idempotent, i.e. it can be called when the |
| 144 | transport is already reading. |
| 145 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 146 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 147 | WriteTransport |
| 148 | -------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 149 | |
| 150 | .. class:: WriteTransport |
| 151 | |
| 152 | Interface for write-only transports. |
| 153 | |
| 154 | .. method:: abort() |
| 155 | |
| 156 | Close the transport immediately, without waiting for pending operations |
| 157 | to complete. Buffered data will be lost. No more data will be received. |
| 158 | The protocol's :meth:`connection_lost` method will eventually be |
| 159 | called with :const:`None` as its argument. |
| 160 | |
| 161 | .. method:: can_write_eof() |
| 162 | |
| 163 | Return :const:`True` if the transport supports :meth:`write_eof`, |
| 164 | :const:`False` if not. |
| 165 | |
| 166 | .. method:: get_write_buffer_size() |
| 167 | |
| 168 | Return the current size of the output buffer used by the transport. |
| 169 | |
Victor Stinner | 52bb949 | 2014-08-26 00:22:28 +0200 | [diff] [blame] | 170 | .. method:: get_write_buffer_limits() |
| 171 | |
| 172 | Get the *high*- and *low*-water limits for write flow control. Return a |
| 173 | tuple ``(low, high)`` where *low* and *high* are positive number of |
| 174 | bytes. |
| 175 | |
| 176 | Use :meth:`set_write_buffer_limits` to set the limits. |
| 177 | |
| 178 | .. versionadded:: 3.4.2 |
| 179 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 180 | .. method:: set_write_buffer_limits(high=None, low=None) |
| 181 | |
| 182 | Set the *high*- and *low*-water limits for write flow control. |
| 183 | |
Kojo Idrissa | 5200a7c | 2017-06-20 14:32:00 -0500 | [diff] [blame] | 184 | These two values (measured in number of |
| 185 | bytes) control when the protocol's |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 186 | :meth:`pause_writing` and :meth:`resume_writing` methods are called. |
| 187 | If specified, the low-water limit must be less than or equal to the |
| 188 | high-water limit. Neither *high* nor *low* can be negative. |
| 189 | |
Kojo Idrissa | 5200a7c | 2017-06-20 14:32:00 -0500 | [diff] [blame] | 190 | :meth:`pause_writing` is called when the buffer size becomes greater |
| 191 | than or equal to the *high* value. If writing has been paused, |
| 192 | :meth:`resume_writing` is called when the buffer size becomes less |
| 193 | than or equal to the *low* value. |
| 194 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 195 | The defaults are implementation-specific. If only the |
Serhiy Storchaka | d65c949 | 2015-11-02 14:10:23 +0200 | [diff] [blame] | 196 | high-water limit is given, the low-water limit defaults to an |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 197 | implementation-specific value less than or equal to the |
| 198 | high-water limit. Setting *high* to zero forces *low* to zero as |
| 199 | well, and causes :meth:`pause_writing` to be called whenever the |
| 200 | buffer becomes non-empty. Setting *low* to zero causes |
| 201 | :meth:`resume_writing` to be called only once the buffer is empty. |
| 202 | Use of zero for either limit is generally sub-optimal as it |
| 203 | reduces opportunities for doing I/O and computation |
| 204 | concurrently. |
| 205 | |
Victor Stinner | 52bb949 | 2014-08-26 00:22:28 +0200 | [diff] [blame] | 206 | Use :meth:`get_write_buffer_limits` to get the limits. |
| 207 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 208 | .. method:: write(data) |
| 209 | |
| 210 | Write some *data* bytes to the transport. |
| 211 | |
| 212 | This method does not block; it buffers the data and arranges for it |
| 213 | to be sent out asynchronously. |
| 214 | |
| 215 | .. method:: writelines(list_of_data) |
| 216 | |
| 217 | Write a list (or any iterable) of data bytes to the transport. |
| 218 | This is functionally equivalent to calling :meth:`write` on each |
| 219 | element yielded by the iterable, but may be implemented more efficiently. |
| 220 | |
| 221 | .. method:: write_eof() |
| 222 | |
| 223 | Close the write end of the transport after flushing buffered data. |
| 224 | Data may still be received. |
| 225 | |
| 226 | This method can raise :exc:`NotImplementedError` if the transport |
| 227 | (e.g. SSL) doesn't support half-closes. |
| 228 | |
| 229 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 230 | DatagramTransport |
| 231 | ----------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 232 | |
| 233 | .. method:: DatagramTransport.sendto(data, addr=None) |
| 234 | |
| 235 | Send the *data* bytes to the remote peer given by *addr* (a |
| 236 | transport-dependent target address). If *addr* is :const:`None`, the |
| 237 | data is sent to the target address given on transport creation. |
| 238 | |
| 239 | This method does not block; it buffers the data and arranges for it |
| 240 | to be sent out asynchronously. |
| 241 | |
| 242 | .. method:: DatagramTransport.abort() |
| 243 | |
| 244 | Close the transport immediately, without waiting for pending operations |
| 245 | to complete. Buffered data will be lost. No more data will be received. |
| 246 | The protocol's :meth:`connection_lost` method will eventually be |
| 247 | called with :const:`None` as its argument. |
| 248 | |
| 249 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 250 | BaseSubprocessTransport |
| 251 | ----------------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 252 | |
| 253 | .. class:: BaseSubprocessTransport |
| 254 | |
| 255 | .. method:: get_pid() |
| 256 | |
| 257 | Return the subprocess process id as an integer. |
| 258 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 259 | .. method:: get_pipe_transport(fd) |
| 260 | |
Brian Curtin | a1afeec | 2014-02-08 18:36:14 -0600 | [diff] [blame] | 261 | Return the transport for the communication pipe corresponding to the |
Victor Stinner | 4270a24 | 2014-10-13 23:56:43 +0200 | [diff] [blame] | 262 | integer file descriptor *fd*: |
| 263 | |
| 264 | * ``0``: readable streaming transport of the standard input (*stdin*), |
| 265 | or :const:`None` if the subprocess was not created with ``stdin=PIPE`` |
| 266 | * ``1``: writable streaming transport of the standard output (*stdout*), |
| 267 | or :const:`None` if the subprocess was not created with ``stdout=PIPE`` |
| 268 | * ``2``: writable streaming transport of the standard error (*stderr*), |
| 269 | or :const:`None` if the subprocess was not created with ``stderr=PIPE`` |
| 270 | * other *fd*: :const:`None` |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 271 | |
Victor Stinner | 933a8c8 | 2013-12-03 01:59:38 +0100 | [diff] [blame] | 272 | .. method:: get_returncode() |
| 273 | |
| 274 | Return the subprocess returncode as an integer or :const:`None` |
| 275 | if it hasn't returned, similarly to the |
| 276 | :attr:`subprocess.Popen.returncode` attribute. |
| 277 | |
Mariatta | 091b84f | 2017-02-27 05:44:15 -0800 | [diff] [blame] | 278 | .. method:: kill() |
Victor Stinner | 933a8c8 | 2013-12-03 01:59:38 +0100 | [diff] [blame] | 279 | |
Martin Panter | d21e0b5 | 2015-10-10 10:36:22 +0000 | [diff] [blame] | 280 | Kill the subprocess, as in :meth:`subprocess.Popen.kill`. |
Victor Stinner | 933a8c8 | 2013-12-03 01:59:38 +0100 | [diff] [blame] | 281 | |
| 282 | On POSIX systems, the function sends SIGKILL to the subprocess. |
| 283 | On Windows, this method is an alias for :meth:`terminate`. |
| 284 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 285 | .. method:: send_signal(signal) |
| 286 | |
| 287 | Send the *signal* number to the subprocess, as in |
| 288 | :meth:`subprocess.Popen.send_signal`. |
| 289 | |
| 290 | .. method:: terminate() |
| 291 | |
| 292 | Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`. |
| 293 | This method is an alias for the :meth:`close` method. |
| 294 | |
| 295 | On POSIX systems, this method sends SIGTERM to the subprocess. |
| 296 | On Windows, the Windows API function TerminateProcess() is called to |
| 297 | stop the subprocess. |
| 298 | |
Victor Stinner | 4270a24 | 2014-10-13 23:56:43 +0200 | [diff] [blame] | 299 | .. method:: close() |
| 300 | |
| 301 | Ask the subprocess to stop by calling the :meth:`terminate` method if the |
| 302 | subprocess hasn't returned yet, and close transports of all pipes |
| 303 | (*stdin*, *stdout* and *stderr*). |
| 304 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 305 | |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 306 | .. _asyncio-protocol: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 307 | |
| 308 | Protocols |
| 309 | ========= |
| 310 | |
| 311 | :mod:`asyncio` provides base classes that you can subclass to implement |
| 312 | your network protocols. Those classes are used in conjunction with |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 313 | :ref:`transports <asyncio-transport>` (see below): the protocol parses incoming |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 314 | data and asks for the writing of outgoing data, while the transport is |
| 315 | responsible for the actual I/O and buffering. |
| 316 | |
| 317 | When subclassing a protocol class, it is recommended you override certain |
| 318 | methods. Those methods are callbacks: they will be called by the transport |
| 319 | on certain events (for example when some data is received); you shouldn't |
| 320 | call them yourself, unless you are implementing a transport. |
| 321 | |
| 322 | .. note:: |
| 323 | All callbacks have default implementations, which are empty. Therefore, |
| 324 | you only need to implement the callbacks for the events in which you |
| 325 | are interested. |
| 326 | |
| 327 | |
| 328 | Protocol classes |
| 329 | ---------------- |
| 330 | |
| 331 | .. class:: Protocol |
| 332 | |
| 333 | The base class for implementing streaming protocols (for use with |
| 334 | e.g. TCP and SSL transports). |
| 335 | |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 336 | .. class:: BufferedProtocol |
| 337 | |
| 338 | A base class for implementing streaming protocols with manual |
| 339 | control of the receive buffer. |
| 340 | |
| 341 | .. versionadded:: 3.7 |
Serhiy Storchaka | bac2d5b | 2018-03-28 22:14:26 +0300 | [diff] [blame] | 342 | **Important:** this has been added to asyncio in Python 3.7 |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 343 | *on a provisional basis*! Treat it as an experimental API that |
| 344 | might be changed or removed in Python 3.8. |
| 345 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 346 | .. class:: DatagramProtocol |
| 347 | |
| 348 | The base class for implementing datagram protocols (for use with |
| 349 | e.g. UDP transports). |
| 350 | |
| 351 | .. class:: SubprocessProtocol |
| 352 | |
| 353 | The base class for implementing protocols communicating with child |
| 354 | processes (through a set of unidirectional pipes). |
| 355 | |
| 356 | |
| 357 | Connection callbacks |
| 358 | -------------------- |
| 359 | |
Victor Stinner | 1538665 | 2014-06-10 09:19:26 +0200 | [diff] [blame] | 360 | These callbacks may be called on :class:`Protocol`, :class:`DatagramProtocol` |
| 361 | and :class:`SubprocessProtocol` instances: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 362 | |
| 363 | .. method:: BaseProtocol.connection_made(transport) |
| 364 | |
| 365 | Called when a connection is made. |
| 366 | |
| 367 | The *transport* argument is the transport representing the |
| 368 | connection. You are responsible for storing it somewhere |
| 369 | (e.g. as an attribute) if you need to. |
| 370 | |
| 371 | .. method:: BaseProtocol.connection_lost(exc) |
| 372 | |
| 373 | Called when the connection is lost or closed. |
| 374 | |
| 375 | The argument is either an exception object or :const:`None`. |
| 376 | The latter means a regular EOF is received, or the connection was |
| 377 | aborted or closed by this side of the connection. |
| 378 | |
Victor Stinner | 1538665 | 2014-06-10 09:19:26 +0200 | [diff] [blame] | 379 | :meth:`~BaseProtocol.connection_made` and :meth:`~BaseProtocol.connection_lost` |
| 380 | are called exactly once per successful connection. All other callbacks will be |
| 381 | called between those two methods, which allows for easier resource management |
| 382 | in your protocol implementation. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 383 | |
| 384 | The following callbacks may be called only on :class:`SubprocessProtocol` |
| 385 | instances: |
| 386 | |
| 387 | .. method:: SubprocessProtocol.pipe_data_received(fd, data) |
| 388 | |
| 389 | Called when the child process writes data into its stdout or stderr pipe. |
| 390 | *fd* is the integer file descriptor of the pipe. *data* is a non-empty |
| 391 | bytes object containing the data. |
| 392 | |
| 393 | .. method:: SubprocessProtocol.pipe_connection_lost(fd, exc) |
| 394 | |
| 395 | Called when one of the pipes communicating with the child process |
| 396 | is closed. *fd* is the integer file descriptor that was closed. |
| 397 | |
| 398 | .. method:: SubprocessProtocol.process_exited() |
| 399 | |
| 400 | Called when the child process has exited. |
| 401 | |
| 402 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 403 | Streaming protocols |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 404 | ------------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 405 | |
| 406 | The following callbacks are called on :class:`Protocol` instances: |
| 407 | |
| 408 | .. method:: Protocol.data_received(data) |
| 409 | |
| 410 | Called when some data is received. *data* is a non-empty bytes object |
| 411 | containing the incoming data. |
| 412 | |
| 413 | .. note:: |
| 414 | Whether the data is buffered, chunked or reassembled depends on |
| 415 | the transport. In general, you shouldn't rely on specific semantics |
| 416 | and instead make your parsing generic and flexible enough. However, |
| 417 | data is always received in the correct order. |
| 418 | |
| 419 | .. method:: Protocol.eof_received() |
| 420 | |
Barry Warsaw | dd9a0a1 | 2017-04-07 14:18:14 -0400 | [diff] [blame] | 421 | Called when the other end signals it won't send any more data |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 422 | (for example by calling :meth:`write_eof`, if the other end also uses |
| 423 | asyncio). |
| 424 | |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 425 | This method may return a false value (including ``None``), in which case |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 426 | the transport will close itself. Conversely, if this method returns a |
| 427 | true value, closing the transport is up to the protocol. Since the |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 428 | default implementation returns ``None``, it implicitly closes the connection. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 429 | |
| 430 | .. note:: |
| 431 | Some transports such as SSL don't support half-closed connections, |
| 432 | in which case returning true from this method will not prevent closing |
| 433 | the connection. |
| 434 | |
| 435 | :meth:`data_received` can be called an arbitrary number of times during |
| 436 | a connection. However, :meth:`eof_received` is called at most once |
| 437 | and, if called, :meth:`data_received` won't be called after it. |
| 438 | |
Victor Stinner | 54a231d | 2015-01-29 13:33:15 +0100 | [diff] [blame] | 439 | State machine: |
| 440 | |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 441 | .. code-block:: none |
| 442 | |
| 443 | start -> connection_made |
| 444 | [-> data_received]* |
| 445 | [-> eof_received]? |
| 446 | -> connection_lost -> end |
| 447 | |
| 448 | |
| 449 | Streaming protocols with manual receive buffer control |
| 450 | ------------------------------------------------------ |
| 451 | |
| 452 | .. versionadded:: 3.7 |
Serhiy Storchaka | bac2d5b | 2018-03-28 22:14:26 +0300 | [diff] [blame] | 453 | **Important:** :class:`BufferedProtocol` has been added to |
Yury Selivanov | 07627e9 | 2018-01-28 23:51:08 -0500 | [diff] [blame] | 454 | asyncio in Python 3.7 *on a provisional basis*! Consider it as an |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 455 | experimental API that might be changed or removed in Python 3.8. |
| 456 | |
| 457 | |
| 458 | Event methods, such as :meth:`AbstractEventLoop.create_server` and |
| 459 | :meth:`AbstractEventLoop.create_connection`, accept factories that |
| 460 | return protocols that implement this interface. |
| 461 | |
| 462 | The idea of BufferedProtocol is that it allows to manually allocate |
| 463 | and control the receive buffer. Event loops can then use the buffer |
| 464 | provided by the protocol to avoid unnecessary data copies. This |
| 465 | can result in noticeable performance improvement for protocols that |
Yury Selivanov | dbf1022 | 2018-05-28 14:31:28 -0400 | [diff] [blame] | 466 | receive big amounts of data. Sophisticated protocols implementations |
| 467 | can allocate the buffer only once at creation time. |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 468 | |
| 469 | The following callbacks are called on :class:`BufferedProtocol` |
| 470 | instances: |
| 471 | |
Yury Selivanov | dbf1022 | 2018-05-28 14:31:28 -0400 | [diff] [blame] | 472 | .. method:: BufferedProtocol.get_buffer(sizehint) |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 473 | |
Yury Selivanov | dbf1022 | 2018-05-28 14:31:28 -0400 | [diff] [blame] | 474 | Called to allocate a new receive buffer. |
| 475 | |
| 476 | *sizehint* is a recommended minimal size for the returned |
| 477 | buffer. It is acceptable to return smaller or bigger buffers |
| 478 | than what *sizehint* suggests. When set to -1, the buffer size |
| 479 | can be arbitrary. It is an error to return a zero-sized buffer. |
| 480 | |
| 481 | Must return an object that implements the |
| 482 | :ref:`buffer protocol <bufferobjects>`. |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 483 | |
| 484 | .. method:: BufferedProtocol.buffer_updated(nbytes) |
| 485 | |
| 486 | Called when the buffer was updated with the received data. |
| 487 | |
| 488 | *nbytes* is the total number of bytes that were written to the buffer. |
| 489 | |
| 490 | .. method:: BufferedProtocol.eof_received() |
| 491 | |
| 492 | See the documentation of the :meth:`Protocol.eof_received` method. |
| 493 | |
| 494 | |
| 495 | :meth:`get_buffer` can be called an arbitrary number of times during |
| 496 | a connection. However, :meth:`eof_received` is called at most once |
Yury Selivanov | 07627e9 | 2018-01-28 23:51:08 -0500 | [diff] [blame] | 497 | and, if called, :meth:`get_buffer` and :meth:`buffer_updated` |
| 498 | won't be called after it. |
Yury Selivanov | 631fd38 | 2018-01-28 16:30:26 -0500 | [diff] [blame] | 499 | |
| 500 | State machine: |
| 501 | |
| 502 | .. code-block:: none |
| 503 | |
| 504 | start -> connection_made |
| 505 | [-> get_buffer |
| 506 | [-> buffer_updated]? |
| 507 | ]* |
| 508 | [-> eof_received]? |
| 509 | -> connection_lost -> end |
Victor Stinner | 54a231d | 2015-01-29 13:33:15 +0100 | [diff] [blame] | 510 | |
| 511 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 512 | Datagram protocols |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 513 | ------------------ |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 514 | |
| 515 | The following callbacks are called on :class:`DatagramProtocol` instances. |
| 516 | |
| 517 | .. method:: DatagramProtocol.datagram_received(data, addr) |
| 518 | |
| 519 | Called when a datagram is received. *data* is a bytes object containing |
| 520 | the incoming data. *addr* is the address of the peer sending the data; |
| 521 | the exact format depends on the transport. |
| 522 | |
| 523 | .. method:: DatagramProtocol.error_received(exc) |
| 524 | |
| 525 | Called when a previous send or receive operation raises an |
| 526 | :class:`OSError`. *exc* is the :class:`OSError` instance. |
| 527 | |
| 528 | This method is called in rare conditions, when the transport (e.g. UDP) |
| 529 | detects that a datagram couldn't be delivered to its recipient. |
| 530 | In many conditions though, undeliverable datagrams will be silently |
| 531 | dropped. |
| 532 | |
| 533 | |
| 534 | Flow control callbacks |
| 535 | ---------------------- |
| 536 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 537 | These callbacks may be called on :class:`Protocol`, |
| 538 | :class:`DatagramProtocol` and :class:`SubprocessProtocol` instances: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 539 | |
| 540 | .. method:: BaseProtocol.pause_writing() |
| 541 | |
| 542 | Called when the transport's buffer goes over the high-water mark. |
| 543 | |
| 544 | .. method:: BaseProtocol.resume_writing() |
| 545 | |
| 546 | Called when the transport's buffer drains below the low-water mark. |
| 547 | |
| 548 | |
| 549 | :meth:`pause_writing` and :meth:`resume_writing` calls are paired -- |
| 550 | :meth:`pause_writing` is called once when the buffer goes strictly over |
| 551 | the high-water mark (even if subsequent writes increases the buffer size |
| 552 | even more), and eventually :meth:`resume_writing` is called once when the |
| 553 | buffer size reaches the low-water mark. |
| 554 | |
| 555 | .. note:: |
| 556 | If the buffer size equals the high-water mark, |
| 557 | :meth:`pause_writing` is not called -- it must go strictly over. |
| 558 | Conversely, :meth:`resume_writing` is called when the buffer size is |
| 559 | equal or lower than the low-water mark. These end conditions |
| 560 | are important to ensure that things go as expected when either |
| 561 | mark is zero. |
| 562 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 563 | .. note:: |
| 564 | On BSD systems (OS X, FreeBSD, etc.) flow control is not supported |
| 565 | for :class:`DatagramProtocol`, because send failures caused by |
| 566 | writing too many packets cannot be detected easily. The socket |
| 567 | always appears 'ready' and excess packets are dropped; an |
| 568 | :class:`OSError` with errno set to :const:`errno.ENOBUFS` may or |
| 569 | may not be raised; if it is raised, it will be reported to |
| 570 | :meth:`DatagramProtocol.error_received` but otherwise ignored. |
| 571 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 572 | |
Victor Stinner | 4b4f9eb | 2014-01-24 17:33:20 +0100 | [diff] [blame] | 573 | Coroutines and protocols |
| 574 | ------------------------ |
| 575 | |
Yury Selivanov | 04356e1 | 2015-06-30 22:13:22 -0400 | [diff] [blame] | 576 | Coroutines can be scheduled in a protocol method using :func:`ensure_future`, |
| 577 | but there is no guarantee made about the execution order. Protocols are not |
| 578 | aware of coroutines created in protocol methods and so will not wait for them. |
Victor Stinner | 4b4f9eb | 2014-01-24 17:33:20 +0100 | [diff] [blame] | 579 | |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 580 | To have a reliable execution order, |
| 581 | use :ref:`stream objects <asyncio-streams>` in a |
| 582 | coroutine with ``await``. For example, the :meth:`StreamWriter.drain` |
Victor Stinner | 4b4f9eb | 2014-01-24 17:33:20 +0100 | [diff] [blame] | 583 | coroutine can be used to wait until the write buffer is flushed. |
| 584 | |
| 585 | |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 586 | Protocol examples |
| 587 | ================= |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 588 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 589 | .. _asyncio-tcp-echo-client-protocol: |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 590 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 591 | TCP echo client protocol |
| 592 | ------------------------ |
| 593 | |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 594 | TCP echo client using the :meth:`AbstractEventLoop.create_connection` method, send |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 595 | data and wait until the connection is closed:: |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 596 | |
| 597 | import asyncio |
| 598 | |
Victor Stinner | cfbea3a | 2014-10-12 11:30:17 +0200 | [diff] [blame] | 599 | class EchoClientProtocol(asyncio.Protocol): |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 600 | def __init__(self, message, loop): |
| 601 | self.message = message |
| 602 | self.loop = loop |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 603 | |
| 604 | def connection_made(self, transport): |
Victor Stinner | 31d8322 | 2013-12-04 11:16:17 +0100 | [diff] [blame] | 605 | transport.write(self.message.encode()) |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 606 | print('Data sent: {!r}'.format(self.message)) |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 607 | |
| 608 | def data_received(self, data): |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 609 | print('Data received: {!r}'.format(data.decode())) |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 610 | |
| 611 | def connection_lost(self, exc): |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 612 | print('The server closed the connection') |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 613 | print('Stop the event loop') |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 614 | self.loop.stop() |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 615 | |
| 616 | loop = asyncio.get_event_loop() |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 617 | message = 'Hello World!' |
| 618 | coro = loop.create_connection(lambda: EchoClientProtocol(message, loop), |
| 619 | '127.0.0.1', 8888) |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 620 | loop.run_until_complete(coro) |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 621 | loop.run_forever() |
| 622 | loop.close() |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 623 | |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 624 | The event loop is running twice. The |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 625 | :meth:`~AbstractEventLoop.run_until_complete` method is preferred in this short |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 626 | example to raise an exception if the server is not listening, instead of |
| 627 | having to write a short coroutine to handle the exception and stop the |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 628 | running loop. At :meth:`~AbstractEventLoop.run_until_complete` exit, the loop is |
Andrew Svetlov | 588517c | 2014-07-23 11:27:17 +0300 | [diff] [blame] | 629 | no longer running, so there is no need to stop the loop in case of an error. |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 630 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 631 | .. seealso:: |
Victor Stinner | c2721b4 | 2014-10-12 11:13:40 +0200 | [diff] [blame] | 632 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 633 | The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>` |
| 634 | example uses the :func:`asyncio.open_connection` function. |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 635 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 636 | |
| 637 | .. _asyncio-tcp-echo-server-protocol: |
| 638 | |
| 639 | TCP echo server protocol |
| 640 | ------------------------ |
| 641 | |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 642 | TCP echo server using the :meth:`AbstractEventLoop.create_server` method, send back |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 643 | received data and close the connection:: |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 644 | |
| 645 | import asyncio |
| 646 | |
Victor Stinner | cfbea3a | 2014-10-12 11:30:17 +0200 | [diff] [blame] | 647 | class EchoServerClientProtocol(asyncio.Protocol): |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 648 | def connection_made(self, transport): |
| 649 | peername = transport.get_extra_info('peername') |
Victor Stinner | c2721b4 | 2014-10-12 11:13:40 +0200 | [diff] [blame] | 650 | print('Connection from {}'.format(peername)) |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 651 | self.transport = transport |
| 652 | |
| 653 | def data_received(self, data): |
Victor Stinner | c2721b4 | 2014-10-12 11:13:40 +0200 | [diff] [blame] | 654 | message = data.decode() |
| 655 | print('Data received: {!r}'.format(message)) |
| 656 | |
| 657 | print('Send: {!r}'.format(message)) |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 658 | self.transport.write(data) |
| 659 | |
Victor Stinner | 5366434 | 2014-10-12 11:35:09 +0200 | [diff] [blame] | 660 | print('Close the client socket') |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 661 | self.transport.close() |
| 662 | |
| 663 | loop = asyncio.get_event_loop() |
Victor Stinner | cfbea3a | 2014-10-12 11:30:17 +0200 | [diff] [blame] | 664 | # Each client connection will create a new protocol instance |
| 665 | coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888) |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 666 | server = loop.run_until_complete(coro) |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 667 | |
Serhiy Storchaka | 0424eaf | 2015-09-12 17:45:25 +0300 | [diff] [blame] | 668 | # Serve requests until Ctrl+C is pressed |
Victor Stinner | c2721b4 | 2014-10-12 11:13:40 +0200 | [diff] [blame] | 669 | print('Serving on {}'.format(server.sockets[0].getsockname())) |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 670 | try: |
| 671 | loop.run_forever() |
| 672 | except KeyboardInterrupt: |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 673 | pass |
Victor Stinner | c2721b4 | 2014-10-12 11:13:40 +0200 | [diff] [blame] | 674 | |
| 675 | # Close the server |
| 676 | server.close() |
| 677 | loop.run_until_complete(server.wait_closed()) |
| 678 | loop.close() |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 679 | |
R David Murray | 530a69f | 2013-12-14 11:26:06 -0500 | [diff] [blame] | 680 | :meth:`Transport.close` can be called immediately after |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 681 | :meth:`WriteTransport.write` even if data are not sent yet on the socket: both |
Andrew Svetlov | 8874342 | 2017-12-11 17:35:49 +0200 | [diff] [blame] | 682 | methods are asynchronous. ``await`` is not needed because these transport |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 683 | methods are not coroutines. |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 684 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 685 | .. seealso:: |
| 686 | |
| 687 | The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>` |
| 688 | example uses the :func:`asyncio.start_server` function. |
| 689 | |
Victor Stinner | c7edffd | 2014-10-12 11:24:26 +0200 | [diff] [blame] | 690 | |
| 691 | .. _asyncio-udp-echo-client-protocol: |
| 692 | |
| 693 | UDP echo client protocol |
| 694 | ------------------------ |
| 695 | |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 696 | UDP echo client using the :meth:`AbstractEventLoop.create_datagram_endpoint` |
Victor Stinner | c7edffd | 2014-10-12 11:24:26 +0200 | [diff] [blame] | 697 | method, send data and close the transport when we received the answer:: |
| 698 | |
| 699 | import asyncio |
| 700 | |
| 701 | class EchoClientProtocol: |
| 702 | def __init__(self, message, loop): |
| 703 | self.message = message |
| 704 | self.loop = loop |
| 705 | self.transport = None |
| 706 | |
| 707 | def connection_made(self, transport): |
| 708 | self.transport = transport |
| 709 | print('Send:', self.message) |
| 710 | self.transport.sendto(self.message.encode()) |
| 711 | |
| 712 | def datagram_received(self, data, addr): |
| 713 | print("Received:", data.decode()) |
| 714 | |
| 715 | print("Close the socket") |
| 716 | self.transport.close() |
| 717 | |
| 718 | def error_received(self, exc): |
| 719 | print('Error received:', exc) |
| 720 | |
| 721 | def connection_lost(self, exc): |
| 722 | print("Socket closed, stop the event loop") |
| 723 | loop = asyncio.get_event_loop() |
| 724 | loop.stop() |
| 725 | |
| 726 | loop = asyncio.get_event_loop() |
| 727 | message = "Hello World!" |
| 728 | connect = loop.create_datagram_endpoint( |
| 729 | lambda: EchoClientProtocol(message, loop), |
| 730 | remote_addr=('127.0.0.1', 9999)) |
| 731 | transport, protocol = loop.run_until_complete(connect) |
| 732 | loop.run_forever() |
| 733 | transport.close() |
| 734 | loop.close() |
| 735 | |
| 736 | |
| 737 | .. _asyncio-udp-echo-server-protocol: |
| 738 | |
| 739 | UDP echo server protocol |
| 740 | ------------------------ |
| 741 | |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 742 | UDP echo server using the :meth:`AbstractEventLoop.create_datagram_endpoint` |
Victor Stinner | c7edffd | 2014-10-12 11:24:26 +0200 | [diff] [blame] | 743 | method, send back received data:: |
| 744 | |
| 745 | import asyncio |
| 746 | |
Victor Stinner | cfbea3a | 2014-10-12 11:30:17 +0200 | [diff] [blame] | 747 | class EchoServerProtocol: |
Victor Stinner | c7edffd | 2014-10-12 11:24:26 +0200 | [diff] [blame] | 748 | def connection_made(self, transport): |
| 749 | self.transport = transport |
| 750 | |
| 751 | def datagram_received(self, data, addr): |
| 752 | message = data.decode() |
| 753 | print('Received %r from %s' % (message, addr)) |
| 754 | print('Send %r to %s' % (message, addr)) |
| 755 | self.transport.sendto(data, addr) |
| 756 | |
| 757 | loop = asyncio.get_event_loop() |
| 758 | print("Starting UDP server") |
Victor Stinner | cfbea3a | 2014-10-12 11:30:17 +0200 | [diff] [blame] | 759 | # One protocol instance will be created to serve all client requests |
Victor Stinner | c7edffd | 2014-10-12 11:24:26 +0200 | [diff] [blame] | 760 | listen = loop.create_datagram_endpoint( |
Victor Stinner | cfbea3a | 2014-10-12 11:30:17 +0200 | [diff] [blame] | 761 | EchoServerProtocol, local_addr=('127.0.0.1', 9999)) |
Victor Stinner | c7edffd | 2014-10-12 11:24:26 +0200 | [diff] [blame] | 762 | transport, protocol = loop.run_until_complete(listen) |
| 763 | |
| 764 | try: |
| 765 | loop.run_forever() |
| 766 | except KeyboardInterrupt: |
| 767 | pass |
| 768 | |
| 769 | transport.close() |
| 770 | loop.close() |
| 771 | |
| 772 | |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 773 | .. _asyncio-register-socket: |
Victor Stinner | a881a7f | 2013-12-09 13:19:23 +0100 | [diff] [blame] | 774 | |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 775 | Register an open socket to wait for data using a protocol |
| 776 | --------------------------------------------------------- |
| 777 | |
| 778 | Wait until a socket receives data using the |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 779 | :meth:`AbstractEventLoop.create_connection` method with a protocol, and then close |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 780 | the event loop :: |
| 781 | |
| 782 | import asyncio |
Victor Stinner | ac577d7 | 2017-11-28 21:33:20 +0100 | [diff] [blame] | 783 | from socket import socketpair |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 784 | |
| 785 | # Create a pair of connected sockets |
Victor Stinner | ccd8e34 | 2014-10-11 16:30:02 +0200 | [diff] [blame] | 786 | rsock, wsock = socketpair() |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 787 | loop = asyncio.get_event_loop() |
| 788 | |
| 789 | class MyProtocol(asyncio.Protocol): |
| 790 | transport = None |
| 791 | |
| 792 | def connection_made(self, transport): |
| 793 | self.transport = transport |
| 794 | |
| 795 | def data_received(self, data): |
| 796 | print("Received:", data.decode()) |
| 797 | |
| 798 | # We are done: close the transport (it will call connection_lost()) |
| 799 | self.transport.close() |
| 800 | |
| 801 | def connection_lost(self, exc): |
| 802 | # The socket has been closed, stop the event loop |
| 803 | loop.stop() |
| 804 | |
| 805 | # Register the socket to wait for data |
| 806 | connect_coro = loop.create_connection(MyProtocol, sock=rsock) |
| 807 | transport, protocol = loop.run_until_complete(connect_coro) |
| 808 | |
| 809 | # Simulate the reception of data from the network |
| 810 | loop.call_soon(wsock.send, 'abc'.encode()) |
| 811 | |
| 812 | # Run the event loop |
| 813 | loop.run_forever() |
| 814 | |
| 815 | # We are done, close sockets and the event loop |
| 816 | rsock.close() |
| 817 | wsock.close() |
| 818 | loop.close() |
| 819 | |
| 820 | .. seealso:: |
| 821 | |
| 822 | The :ref:`watch a file descriptor for read events |
| 823 | <asyncio-watch-read-event>` example uses the low-level |
Guido van Rossum | f68afd8 | 2016-08-08 09:41:21 -0700 | [diff] [blame] | 824 | :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 825 | socket. |
| 826 | |
| 827 | The :ref:`register an open socket to wait for data using streams |
| 828 | <asyncio-register-socket-streams>` example uses high-level streams |
| 829 | created by the :func:`open_connection` function in a coroutine. |