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