Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 1 | .. module:: asyncio |
| 2 | |
Victor Stinner | 1ca5ba6 | 2013-12-03 01:49:43 +0100 | [diff] [blame] | 3 | ++++++++++++++++++++++++ |
| 4 | Transports and protocols |
| 5 | ++++++++++++++++++++++++ |
| 6 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 7 | .. _transport: |
| 8 | |
| 9 | Transports |
| 10 | ========== |
| 11 | |
| 12 | Transports are classed provided by :mod:`asyncio` in order to abstract |
| 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 |
| 19 | paired with a :ref:`protocol <protocol>` instance. The protocol can |
| 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 |
| 92 | the protocol's :meth:`data_received` method until meth:`resume_reading` |
| 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 | |
| 124 | .. method:: set_write_buffer_limits(high=None, low=None) |
| 125 | |
| 126 | Set the *high*- and *low*-water limits for write flow control. |
| 127 | |
| 128 | These two values control when call the protocol's |
| 129 | :meth:`pause_writing` and :meth:`resume_writing` methods are called. |
| 130 | If specified, the low-water limit must be less than or equal to the |
| 131 | high-water limit. Neither *high* nor *low* can be negative. |
| 132 | |
| 133 | The defaults are implementation-specific. If only the |
| 134 | high-water limit is given, the low-water limit defaults to a |
| 135 | implementation-specific value less than or equal to the |
| 136 | high-water limit. Setting *high* to zero forces *low* to zero as |
| 137 | well, and causes :meth:`pause_writing` to be called whenever the |
| 138 | buffer becomes non-empty. Setting *low* to zero causes |
| 139 | :meth:`resume_writing` to be called only once the buffer is empty. |
| 140 | Use of zero for either limit is generally sub-optimal as it |
| 141 | reduces opportunities for doing I/O and computation |
| 142 | concurrently. |
| 143 | |
| 144 | .. method:: write(data) |
| 145 | |
| 146 | Write some *data* bytes to the transport. |
| 147 | |
| 148 | This method does not block; it buffers the data and arranges for it |
| 149 | to be sent out asynchronously. |
| 150 | |
| 151 | .. method:: writelines(list_of_data) |
| 152 | |
| 153 | Write a list (or any iterable) of data bytes to the transport. |
| 154 | This is functionally equivalent to calling :meth:`write` on each |
| 155 | element yielded by the iterable, but may be implemented more efficiently. |
| 156 | |
| 157 | .. method:: write_eof() |
| 158 | |
| 159 | Close the write end of the transport after flushing buffered data. |
| 160 | Data may still be received. |
| 161 | |
| 162 | This method can raise :exc:`NotImplementedError` if the transport |
| 163 | (e.g. SSL) doesn't support half-closes. |
| 164 | |
| 165 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 166 | DatagramTransport |
| 167 | ----------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 168 | |
| 169 | .. method:: DatagramTransport.sendto(data, addr=None) |
| 170 | |
| 171 | Send the *data* bytes to the remote peer given by *addr* (a |
| 172 | transport-dependent target address). If *addr* is :const:`None`, the |
| 173 | data is sent to the target address given on transport creation. |
| 174 | |
| 175 | This method does not block; it buffers the data and arranges for it |
| 176 | to be sent out asynchronously. |
| 177 | |
| 178 | .. method:: DatagramTransport.abort() |
| 179 | |
| 180 | Close the transport immediately, without waiting for pending operations |
| 181 | to complete. Buffered data will be lost. No more data will be received. |
| 182 | The protocol's :meth:`connection_lost` method will eventually be |
| 183 | called with :const:`None` as its argument. |
| 184 | |
| 185 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 186 | BaseSubprocessTransport |
| 187 | ----------------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 188 | |
| 189 | .. class:: BaseSubprocessTransport |
| 190 | |
| 191 | .. method:: get_pid() |
| 192 | |
| 193 | Return the subprocess process id as an integer. |
| 194 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 195 | .. method:: get_pipe_transport(fd) |
| 196 | |
| 197 | Return the transport for the communication pipe correspondong to the |
| 198 | integer file descriptor *fd*. The return value can be a readable or |
| 199 | writable streaming transport, depending on the *fd*. If *fd* doesn't |
| 200 | correspond to a pipe belonging to this transport, :const:`None` is |
| 201 | returned. |
| 202 | |
Victor Stinner | 933a8c8 | 2013-12-03 01:59:38 +0100 | [diff] [blame] | 203 | .. method:: get_returncode() |
| 204 | |
| 205 | Return the subprocess returncode as an integer or :const:`None` |
| 206 | if it hasn't returned, similarly to the |
| 207 | :attr:`subprocess.Popen.returncode` attribute. |
| 208 | |
| 209 | .. method:: kill(self) |
| 210 | |
| 211 | Kill the subprocess, as in :meth:`subprocess.Popen.kill` |
| 212 | |
| 213 | On POSIX systems, the function sends SIGKILL to the subprocess. |
| 214 | On Windows, this method is an alias for :meth:`terminate`. |
| 215 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 216 | .. method:: send_signal(signal) |
| 217 | |
| 218 | Send the *signal* number to the subprocess, as in |
| 219 | :meth:`subprocess.Popen.send_signal`. |
| 220 | |
| 221 | .. method:: terminate() |
| 222 | |
| 223 | Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`. |
| 224 | This method is an alias for the :meth:`close` method. |
| 225 | |
| 226 | On POSIX systems, this method sends SIGTERM to the subprocess. |
| 227 | On Windows, the Windows API function TerminateProcess() is called to |
| 228 | stop the subprocess. |
| 229 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 230 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 231 | StreamWriter |
| 232 | ------------ |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 233 | |
| 234 | .. class:: StreamWriter(transport, protocol, reader, loop) |
| 235 | |
| 236 | Wraps a Transport. |
| 237 | |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame^] | 238 | This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`, |
| 239 | :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds |
| 240 | :meth:`drain` which returns an optional :class:`Future` on which you can |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 241 | wait for flow control. It also adds a transport attribute which references |
| 242 | the :class:`Transport` directly. |
| 243 | |
| 244 | .. attribute:: transport |
| 245 | |
| 246 | Transport. |
| 247 | |
| 248 | .. method:: close() |
| 249 | |
| 250 | Close the transport: see :meth:`BaseTransport.close`. |
| 251 | |
| 252 | .. method:: drain() |
| 253 | |
| 254 | This method has an unusual return value. |
| 255 | |
| 256 | The intended use is to write:: |
| 257 | |
| 258 | w.write(data) |
| 259 | yield from w.drain() |
| 260 | |
| 261 | When there's nothing to wait for, :meth:`drain()` returns ``()``, and the |
| 262 | yield-from continues immediately. When the transport buffer is full (the |
| 263 | protocol is paused), :meth:`drain` creates and returns a |
Victor Stinner | 99c2ab4 | 2013-12-03 19:17:25 +0100 | [diff] [blame^] | 264 | :class:`Future` and the yield-from will block until |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 265 | that Future is completed, which will happen when the buffer is |
| 266 | (partially) drained and the protocol is resumed. |
| 267 | |
| 268 | .. method:: get_extra_info(name, default=None) |
| 269 | |
| 270 | Return optional transport information: see |
| 271 | :meth:`BaseTransport.get_extra_info`. |
| 272 | |
| 273 | .. method:: write(data) |
| 274 | |
| 275 | Write some *data* bytes to the transport: see |
| 276 | :meth:`WriteTransport.write`. |
| 277 | |
| 278 | .. method:: writelines(data) |
| 279 | |
| 280 | Write a list (or any iterable) of data bytes to the transport: |
| 281 | see :meth:`WriteTransport.writelines`. |
| 282 | |
| 283 | .. method:: can_write_eof() |
| 284 | |
| 285 | Return :const:`True` if the transport supports :meth:`write_eof`, |
| 286 | :const:`False` if not. See :meth:`WriteTransport.can_write_eof`. |
| 287 | |
| 288 | .. method:: write_eof() |
| 289 | |
| 290 | Close the write end of the transport after flushing buffered data: |
| 291 | see :meth:`WriteTransport.write_eof`. |
| 292 | |
| 293 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 294 | StreamReader |
| 295 | ------------ |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 296 | |
| 297 | .. class:: StreamReader(limit=_DEFAULT_LIMIT, loop=None) |
| 298 | |
| 299 | .. method:: exception() |
| 300 | |
| 301 | Get the exception. |
| 302 | |
| 303 | .. method:: feed_eof() |
| 304 | |
| 305 | XXX |
| 306 | |
| 307 | .. method:: feed_data(data) |
| 308 | |
| 309 | XXX |
| 310 | |
| 311 | .. method:: set_exception(exc) |
| 312 | |
| 313 | Set the exception. |
| 314 | |
| 315 | .. method:: set_transport(transport) |
| 316 | |
| 317 | Set the transport. |
| 318 | |
| 319 | .. method:: read(n=-1) |
| 320 | |
| 321 | XXX |
| 322 | |
| 323 | This method returns a :ref:`coroutine <coroutine>`. |
| 324 | |
| 325 | .. method:: readline() |
| 326 | |
| 327 | XXX |
| 328 | |
| 329 | This method returns a :ref:`coroutine <coroutine>`. |
| 330 | |
| 331 | .. method:: readexactly(n) |
| 332 | |
| 333 | XXX |
| 334 | |
| 335 | This method returns a :ref:`coroutine <coroutine>`. |
| 336 | |
| 337 | |
| 338 | |
| 339 | .. _protocol: |
| 340 | |
| 341 | Protocols |
| 342 | ========= |
| 343 | |
| 344 | :mod:`asyncio` provides base classes that you can subclass to implement |
| 345 | your network protocols. Those classes are used in conjunction with |
| 346 | :ref:`transports <transport>` (see below): the protocol parses incoming |
| 347 | data and asks for the writing of outgoing data, while the transport is |
| 348 | responsible for the actual I/O and buffering. |
| 349 | |
| 350 | When subclassing a protocol class, it is recommended you override certain |
| 351 | methods. Those methods are callbacks: they will be called by the transport |
| 352 | on certain events (for example when some data is received); you shouldn't |
| 353 | call them yourself, unless you are implementing a transport. |
| 354 | |
| 355 | .. note:: |
| 356 | All callbacks have default implementations, which are empty. Therefore, |
| 357 | you only need to implement the callbacks for the events in which you |
| 358 | are interested. |
| 359 | |
| 360 | |
| 361 | Protocol classes |
| 362 | ---------------- |
| 363 | |
| 364 | .. class:: Protocol |
| 365 | |
| 366 | The base class for implementing streaming protocols (for use with |
| 367 | e.g. TCP and SSL transports). |
| 368 | |
| 369 | .. class:: DatagramProtocol |
| 370 | |
| 371 | The base class for implementing datagram protocols (for use with |
| 372 | e.g. UDP transports). |
| 373 | |
| 374 | .. class:: SubprocessProtocol |
| 375 | |
| 376 | The base class for implementing protocols communicating with child |
| 377 | processes (through a set of unidirectional pipes). |
| 378 | |
| 379 | |
| 380 | Connection callbacks |
| 381 | -------------------- |
| 382 | |
| 383 | These callbacks may be called on :class:`Protocol` and |
| 384 | :class:`SubprocessProtocol` instances: |
| 385 | |
| 386 | .. method:: BaseProtocol.connection_made(transport) |
| 387 | |
| 388 | Called when a connection is made. |
| 389 | |
| 390 | The *transport* argument is the transport representing the |
| 391 | connection. You are responsible for storing it somewhere |
| 392 | (e.g. as an attribute) if you need to. |
| 393 | |
| 394 | .. method:: BaseProtocol.connection_lost(exc) |
| 395 | |
| 396 | Called when the connection is lost or closed. |
| 397 | |
| 398 | The argument is either an exception object or :const:`None`. |
| 399 | The latter means a regular EOF is received, or the connection was |
| 400 | aborted or closed by this side of the connection. |
| 401 | |
| 402 | :meth:`connection_made` and :meth:`connection_lost` are called exactly once |
| 403 | per successful connection. All other callbacks will be called between those |
| 404 | two methods, which allows for easier resource management in your protocol |
| 405 | implementation. |
| 406 | |
| 407 | The following callbacks may be called only on :class:`SubprocessProtocol` |
| 408 | instances: |
| 409 | |
| 410 | .. method:: SubprocessProtocol.pipe_data_received(fd, data) |
| 411 | |
| 412 | Called when the child process writes data into its stdout or stderr pipe. |
| 413 | *fd* is the integer file descriptor of the pipe. *data* is a non-empty |
| 414 | bytes object containing the data. |
| 415 | |
| 416 | .. method:: SubprocessProtocol.pipe_connection_lost(fd, exc) |
| 417 | |
| 418 | Called when one of the pipes communicating with the child process |
| 419 | is closed. *fd* is the integer file descriptor that was closed. |
| 420 | |
| 421 | .. method:: SubprocessProtocol.process_exited() |
| 422 | |
| 423 | Called when the child process has exited. |
| 424 | |
| 425 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 426 | Streaming protocols |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 427 | ------------------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 428 | |
| 429 | The following callbacks are called on :class:`Protocol` instances: |
| 430 | |
| 431 | .. method:: Protocol.data_received(data) |
| 432 | |
| 433 | Called when some data is received. *data* is a non-empty bytes object |
| 434 | containing the incoming data. |
| 435 | |
| 436 | .. note:: |
| 437 | Whether the data is buffered, chunked or reassembled depends on |
| 438 | the transport. In general, you shouldn't rely on specific semantics |
| 439 | and instead make your parsing generic and flexible enough. However, |
| 440 | data is always received in the correct order. |
| 441 | |
| 442 | .. method:: Protocol.eof_received() |
| 443 | |
| 444 | Calls when the other end signals it won't send any more data |
| 445 | (for example by calling :meth:`write_eof`, if the other end also uses |
| 446 | asyncio). |
| 447 | |
| 448 | This method may return a false value (including None), in which case |
| 449 | the transport will close itself. Conversely, if this method returns a |
| 450 | true value, closing the transport is up to the protocol. Since the |
| 451 | default implementation returns None, it implicitly closes the connection. |
| 452 | |
| 453 | .. note:: |
| 454 | Some transports such as SSL don't support half-closed connections, |
| 455 | in which case returning true from this method will not prevent closing |
| 456 | the connection. |
| 457 | |
| 458 | :meth:`data_received` can be called an arbitrary number of times during |
| 459 | a connection. However, :meth:`eof_received` is called at most once |
| 460 | and, if called, :meth:`data_received` won't be called after it. |
| 461 | |
| 462 | Datagram protocols |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 463 | ------------------ |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 464 | |
| 465 | The following callbacks are called on :class:`DatagramProtocol` instances. |
| 466 | |
| 467 | .. method:: DatagramProtocol.datagram_received(data, addr) |
| 468 | |
| 469 | Called when a datagram is received. *data* is a bytes object containing |
| 470 | the incoming data. *addr* is the address of the peer sending the data; |
| 471 | the exact format depends on the transport. |
| 472 | |
| 473 | .. method:: DatagramProtocol.error_received(exc) |
| 474 | |
| 475 | Called when a previous send or receive operation raises an |
| 476 | :class:`OSError`. *exc* is the :class:`OSError` instance. |
| 477 | |
| 478 | This method is called in rare conditions, when the transport (e.g. UDP) |
| 479 | detects that a datagram couldn't be delivered to its recipient. |
| 480 | In many conditions though, undeliverable datagrams will be silently |
| 481 | dropped. |
| 482 | |
| 483 | |
| 484 | Flow control callbacks |
| 485 | ---------------------- |
| 486 | |
| 487 | These callbacks may be called on :class:`Protocol` and |
| 488 | :class:`SubprocessProtocol` instances: |
| 489 | |
| 490 | .. method:: BaseProtocol.pause_writing() |
| 491 | |
| 492 | Called when the transport's buffer goes over the high-water mark. |
| 493 | |
| 494 | .. method:: BaseProtocol.resume_writing() |
| 495 | |
| 496 | Called when the transport's buffer drains below the low-water mark. |
| 497 | |
| 498 | |
| 499 | :meth:`pause_writing` and :meth:`resume_writing` calls are paired -- |
| 500 | :meth:`pause_writing` is called once when the buffer goes strictly over |
| 501 | the high-water mark (even if subsequent writes increases the buffer size |
| 502 | even more), and eventually :meth:`resume_writing` is called once when the |
| 503 | buffer size reaches the low-water mark. |
| 504 | |
| 505 | .. note:: |
| 506 | If the buffer size equals the high-water mark, |
| 507 | :meth:`pause_writing` is not called -- it must go strictly over. |
| 508 | Conversely, :meth:`resume_writing` is called when the buffer size is |
| 509 | equal or lower than the low-water mark. These end conditions |
| 510 | are important to ensure that things go as expected when either |
| 511 | mark is zero. |
| 512 | |
| 513 | |
| 514 | Server |
| 515 | ------ |
| 516 | |
| 517 | .. class:: AbstractServer |
| 518 | |
Victor Stinner | cf6f72e | 2013-12-03 18:23:52 +0100 | [diff] [blame] | 519 | Abstract server returned by :func:`BaseEventLoop.create_server`. |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 520 | |
| 521 | .. method:: close() |
| 522 | |
| 523 | Stop serving. This leaves existing connections open. |
| 524 | |
| 525 | .. method:: wait_closed() |
| 526 | |
| 527 | Coroutine to wait until service is closed. |
| 528 | |
| 529 | |
| 530 | Network functions |
| 531 | ================= |
| 532 | |
| 533 | .. function:: open_connection(host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds) |
| 534 | |
| 535 | A wrapper for create_connection() returning a (reader, writer) pair. |
| 536 | |
| 537 | The reader returned is a StreamReader instance; the writer is a |
| 538 | :class:`Transport`. |
| 539 | |
| 540 | The arguments are all the usual arguments to |
| 541 | :meth:`BaseEventLoop.create_connection` except *protocol_factory*; most |
| 542 | common are positional host and port, with various optional keyword arguments |
| 543 | following. |
| 544 | |
| 545 | Additional optional keyword arguments are *loop* (to set the event loop |
| 546 | instance to use) and *limit* (to set the buffer limit passed to the |
| 547 | StreamReader). |
| 548 | |
| 549 | (If you want to customize the :class:`StreamReader` and/or |
| 550 | :class:`StreamReaderProtocol` classes, just copy the code -- there's really |
| 551 | nothing special here except some convenience.) |
| 552 | |
| 553 | This function returns a :ref:`coroutine <coroutine>`. |
| 554 | |
| 555 | .. function:: start_server(client_connected_cb, host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds) |
| 556 | |
| 557 | Start a socket server, call back for each client connected. |
| 558 | |
| 559 | The first parameter, *client_connected_cb*, takes two parameters: |
| 560 | *client_reader*, *client_writer*. *client_reader* is a |
| 561 | :class:`StreamReader` object, while *client_writer* is a |
| 562 | :class:`StreamWriter` object. This parameter can either be a plain callback |
| 563 | function or a :ref:`coroutine <coroutine>`; if it is a coroutine, it will be |
| 564 | automatically converted into a :class:`Task`. |
| 565 | |
| 566 | The rest of the arguments are all the usual arguments to |
| 567 | :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most |
| 568 | common are positional host and port, with various optional keyword arguments |
| 569 | following. The return value is the same as |
| 570 | :meth:`~BaseEventLoop.create_server()`. |
| 571 | |
| 572 | Additional optional keyword arguments are *loop* (to set the event loop |
| 573 | instance to use) and *limit* (to set the buffer limit passed to the |
| 574 | :class:`StreamReader`). |
| 575 | |
| 576 | The return value is the same as :meth:`~BaseEventLoop.create_server()`, i.e. |
| 577 | a :class:`AbstractServer` object which can be used to stop the service. |
| 578 | |
| 579 | This function returns a :ref:`coroutine <coroutine>`. |
| 580 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 581 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 582 | Protocol example: TCP echo client and server |
| 583 | ============================================ |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 584 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 585 | Echo server |
| 586 | ----------- |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 587 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 588 | TCP echo server example:: |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 589 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 590 | import asyncio |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 591 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 592 | class EchoServer(asyncio.Protocol): |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 593 | def connection_made(self, transport): |
| 594 | print('connection made') |
| 595 | self.transport = transport |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 596 | |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 597 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 598 | def data_received(self, data): |
| 599 | print('data received:', data.decode()) |
| 600 | self.transport.write(data) |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 601 | |
Victor Stinner | 15faa9c | 2013-12-03 15:04:18 +0100 | [diff] [blame] | 602 | # close the socket |
| 603 | self.transport.close() |
| 604 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 605 | def connection_lost(self, exc): |
| 606 | print('connection lost') |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 607 | |
Victor Stinner | 0c6f1ca | 2013-12-03 01:46:39 +0100 | [diff] [blame] | 608 | loop = asyncio.get_event_loop() |
| 609 | f = loop.create_server(EchoServer, '127.0.0.1', 8888) |
| 610 | s = loop.run_until_complete(f) |
| 611 | print('serving on', s.sockets[0].getsockname()) |
| 612 | loop.run_forever() |
| 613 | |
| 614 | |
| 615 | Echo client |
| 616 | ----------- |
| 617 | |
| 618 | TCP echo client example:: |
| 619 | |
| 620 | import asyncio |
| 621 | |
| 622 | class EchoClient(asyncio.Protocol): |
| 623 | message = 'This is the message. It will be echoed.' |
| 624 | |
| 625 | def connection_made(self, transport): |
| 626 | self.transport = transport |
| 627 | self.transport.write(self.message.encode()) |
| 628 | print('data sent:', self.message) |
| 629 | |
| 630 | def data_received(self, data): |
| 631 | print('data received:', data.decode()) |
| 632 | |
| 633 | def connection_lost(self, exc): |
| 634 | print('connection lost') |
| 635 | asyncio.get_event_loop().stop() |
| 636 | |
| 637 | loop = asyncio.get_event_loop() |
| 638 | task = loop.create_connection(EchoClient, '127.0.0.1', 8888) |
| 639 | loop.run_until_complete(task) |
| 640 | loop.run_forever() |
| 641 | loop.close() |
Victor Stinner | ea3183f | 2013-12-03 01:08:00 +0100 | [diff] [blame] | 642 | |