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