blob: cd84ae76b5d86e0fbd6b7bee880e930cda683c6e [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
lf627d2c82017-07-25 17:03:51 -06003+++++++++++++++++++++++++++++++++++++++++++++
4Transports and protocols (callback based API)
5+++++++++++++++++++++++++++++++++++++++++++++
6
7**Source code:** :source:`Lib/asyncio/transports.py`
8
9**Source code:** :source:`Lib/asyncio/protocols.py`
Victor Stinner1ca5ba62013-12-03 01:49:43 +010010
Victor Stinner9592edb2014-02-02 15:03:02 +010011.. _asyncio-transport:
Victor Stinnerea3183f2013-12-03 01:08:00 +010012
13Transports
14==========
15
Guido van Rossum589872c2014-03-29 21:14:04 -070016Transports are classes provided by :mod:`asyncio` in order to abstract
Victor Stinnerea3183f2013-12-03 01:08:00 +010017various kinds of communication channels. You generally won't instantiate
Martin Panterd210a702016-08-20 08:03:06 +000018a transport yourself; instead, you will call an :class:`AbstractEventLoop` method
Victor Stinnerea3183f2013-12-03 01:08:00 +010019which will create the transport and try to initiate the underlying
20communication channel, calling you back when it succeeds.
21
22Once the communication channel is established, a transport is always
Victor Stinner9592edb2014-02-02 15:03:02 +010023paired with a :ref:`protocol <asyncio-protocol>` instance. The protocol can
Victor Stinnerea3183f2013-12-03 01:08:00 +010024then call the transport's methods for various purposes.
25
26:mod:`asyncio` currently implements transports for TCP, UDP, SSL, and
27subprocess pipes. The methods available on a transport depend on
28the transport's kind.
29
Victor Stinner83704962015-02-25 14:24:15 +010030The transport classes are :ref:`not thread safe <asyncio-multithreading>`.
31
Yury Selivanov3432f2f2016-12-12 16:44:58 -050032.. versionchanged:: 3.6
33 The socket option ``TCP_NODELAY`` is now set by default.
34
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
Victor Stinner0c6f1ca2013-12-03 01:46:39 +010036BaseTransport
37-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010038
39.. class:: BaseTransport
40
41 Base class for transports.
42
Mariatta091b84f2017-02-27 05:44:15 -080043 .. method:: close()
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
45 Close the transport. If the transport has a buffer for outgoing
46 data, buffered data will be flushed asynchronously. No more data
47 will be received. After all buffered data is flushed, the
48 protocol's :meth:`connection_lost` method will be called with
49 :const:`None` as its argument.
50
Mariatta091b84f2017-02-27 05:44:15 -080051 .. method:: is_closing()
Yury Selivanov1744d532015-11-16 12:46:41 -050052
53 Return ``True`` if the transport is closing or is closed.
54
Yury Selivanov344904c2015-11-16 12:47:15 -050055 .. versionadded:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010056
57 .. method:: get_extra_info(name, default=None)
58
59 Return optional transport information. *name* is a string representing
60 the piece of transport-specific information to get, *default* is the
61 value to return if the information doesn't exist.
62
63 This method allows transport implementations to easily expose
64 channel-specific information.
65
66 * socket:
67
68 - ``'peername'``: the remote address to which the socket is connected,
69 result of :meth:`socket.socket.getpeername` (``None`` on error)
70 - ``'socket'``: :class:`socket.socket` instance
71 - ``'sockname'``: the socket's own address,
72 result of :meth:`socket.socket.getsockname`
73
74 * SSL socket:
75
76 - ``'compression'``: the compression algorithm being used as a string,
77 or ``None`` if the connection isn't compressed; result of
78 :meth:`ssl.SSLSocket.compression`
79 - ``'cipher'``: a three-value tuple containing the name of the cipher
80 being used, the version of the SSL protocol that defines its use, and
81 the number of secret bits being used; result of
82 :meth:`ssl.SSLSocket.cipher`
83 - ``'peercert'``: peer certificate; result of
84 :meth:`ssl.SSLSocket.getpeercert`
85 - ``'sslcontext'``: :class:`ssl.SSLContext` instance
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +020086 - ``'ssl_object'``: :class:`ssl.SSLObject` or :class:`ssl.SSLSocket`
87 instance
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
89 * pipe:
90
91 - ``'pipe'``: pipe object
92
93 * subprocess:
94
95 - ``'subprocess'``: :class:`subprocess.Popen` instance
96
Berker Peksag2ebd6fe2016-11-07 23:36:14 +030097 .. method:: set_protocol(protocol)
INADA Naoki1ea023e2016-11-04 16:33:47 +090098
99 Set a new protocol. Switching protocol should only be done when both
100 protocols are documented to support the switch.
101
Berker Peksag2ebd6fe2016-11-07 23:36:14 +0300102 .. versionadded:: 3.5.3
INADA Naoki1ea023e2016-11-04 16:33:47 +0900103
Berker Peksag2ebd6fe2016-11-07 23:36:14 +0300104 .. method:: get_protocol
INADA Naoki1ea023e2016-11-04 16:33:47 +0900105
106 Return the current protocol.
107
Berker Peksag2ebd6fe2016-11-07 23:36:14 +0300108 .. versionadded:: 3.5.3
INADA Naoki1ea023e2016-11-04 16:33:47 +0900109
Victor Stinner04ce06b2015-09-21 18:27:52 +0200110 .. versionchanged:: 3.5.1
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200111 ``'ssl_object'`` info was added to SSL sockets.
112
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100114ReadTransport
115-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116
117.. class:: ReadTransport
118
119 Interface for read-only transports.
120
121 .. method:: pause_reading()
122
123 Pause the receiving end of the transport. No data will be passed to
Victor Stinner51f31292014-03-21 17:17:15 +0100124 the protocol's :meth:`data_received` method until :meth:`resume_reading`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100125 is called.
126
127 .. method:: resume_reading()
128
129 Resume the receiving end. The protocol's :meth:`data_received` method
130 will be called once again if some data is available for reading.
131
132
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100133WriteTransport
134--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100135
136.. class:: WriteTransport
137
138 Interface for write-only transports.
139
140 .. method:: abort()
141
142 Close the transport immediately, without waiting for pending operations
143 to complete. Buffered data will be lost. No more data will be received.
144 The protocol's :meth:`connection_lost` method will eventually be
145 called with :const:`None` as its argument.
146
147 .. method:: can_write_eof()
148
149 Return :const:`True` if the transport supports :meth:`write_eof`,
150 :const:`False` if not.
151
152 .. method:: get_write_buffer_size()
153
154 Return the current size of the output buffer used by the transport.
155
Victor Stinner52bb9492014-08-26 00:22:28 +0200156 .. method:: get_write_buffer_limits()
157
158 Get the *high*- and *low*-water limits for write flow control. Return a
159 tuple ``(low, high)`` where *low* and *high* are positive number of
160 bytes.
161
162 Use :meth:`set_write_buffer_limits` to set the limits.
163
164 .. versionadded:: 3.4.2
165
Victor Stinnerea3183f2013-12-03 01:08:00 +0100166 .. method:: set_write_buffer_limits(high=None, low=None)
167
168 Set the *high*- and *low*-water limits for write flow control.
169
Kojo Idrissa5200a7c2017-06-20 14:32:00 -0500170 These two values (measured in number of
171 bytes) control when the protocol's
Victor Stinnerea3183f2013-12-03 01:08:00 +0100172 :meth:`pause_writing` and :meth:`resume_writing` methods are called.
173 If specified, the low-water limit must be less than or equal to the
174 high-water limit. Neither *high* nor *low* can be negative.
175
Kojo Idrissa5200a7c2017-06-20 14:32:00 -0500176 :meth:`pause_writing` is called when the buffer size becomes greater
177 than or equal to the *high* value. If writing has been paused,
178 :meth:`resume_writing` is called when the buffer size becomes less
179 than or equal to the *low* value.
180
Victor Stinnerea3183f2013-12-03 01:08:00 +0100181 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200182 high-water limit is given, the low-water limit defaults to an
Victor Stinnerea3183f2013-12-03 01:08:00 +0100183 implementation-specific value less than or equal to the
184 high-water limit. Setting *high* to zero forces *low* to zero as
185 well, and causes :meth:`pause_writing` to be called whenever the
186 buffer becomes non-empty. Setting *low* to zero causes
187 :meth:`resume_writing` to be called only once the buffer is empty.
188 Use of zero for either limit is generally sub-optimal as it
189 reduces opportunities for doing I/O and computation
190 concurrently.
191
Victor Stinner52bb9492014-08-26 00:22:28 +0200192 Use :meth:`get_write_buffer_limits` to get the limits.
193
Victor Stinnerea3183f2013-12-03 01:08:00 +0100194 .. method:: write(data)
195
196 Write some *data* bytes to the transport.
197
198 This method does not block; it buffers the data and arranges for it
199 to be sent out asynchronously.
200
201 .. method:: writelines(list_of_data)
202
203 Write a list (or any iterable) of data bytes to the transport.
204 This is functionally equivalent to calling :meth:`write` on each
205 element yielded by the iterable, but may be implemented more efficiently.
206
207 .. method:: write_eof()
208
209 Close the write end of the transport after flushing buffered data.
210 Data may still be received.
211
212 This method can raise :exc:`NotImplementedError` if the transport
213 (e.g. SSL) doesn't support half-closes.
214
215
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100216DatagramTransport
217-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
219.. method:: DatagramTransport.sendto(data, addr=None)
220
221 Send the *data* bytes to the remote peer given by *addr* (a
222 transport-dependent target address). If *addr* is :const:`None`, the
223 data is sent to the target address given on transport creation.
224
225 This method does not block; it buffers the data and arranges for it
226 to be sent out asynchronously.
227
228.. method:: DatagramTransport.abort()
229
230 Close the transport immediately, without waiting for pending operations
231 to complete. Buffered data will be lost. No more data will be received.
232 The protocol's :meth:`connection_lost` method will eventually be
233 called with :const:`None` as its argument.
234
235
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100236BaseSubprocessTransport
237-----------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100238
239.. class:: BaseSubprocessTransport
240
241 .. method:: get_pid()
242
243 Return the subprocess process id as an integer.
244
Victor Stinnerea3183f2013-12-03 01:08:00 +0100245 .. method:: get_pipe_transport(fd)
246
Brian Curtina1afeec2014-02-08 18:36:14 -0600247 Return the transport for the communication pipe corresponding to the
Victor Stinner4270a242014-10-13 23:56:43 +0200248 integer file descriptor *fd*:
249
250 * ``0``: readable streaming transport of the standard input (*stdin*),
251 or :const:`None` if the subprocess was not created with ``stdin=PIPE``
252 * ``1``: writable streaming transport of the standard output (*stdout*),
253 or :const:`None` if the subprocess was not created with ``stdout=PIPE``
254 * ``2``: writable streaming transport of the standard error (*stderr*),
255 or :const:`None` if the subprocess was not created with ``stderr=PIPE``
256 * other *fd*: :const:`None`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100257
Victor Stinner933a8c82013-12-03 01:59:38 +0100258 .. method:: get_returncode()
259
260 Return the subprocess returncode as an integer or :const:`None`
261 if it hasn't returned, similarly to the
262 :attr:`subprocess.Popen.returncode` attribute.
263
Mariatta091b84f2017-02-27 05:44:15 -0800264 .. method:: kill()
Victor Stinner933a8c82013-12-03 01:59:38 +0100265
Martin Panterd21e0b52015-10-10 10:36:22 +0000266 Kill the subprocess, as in :meth:`subprocess.Popen.kill`.
Victor Stinner933a8c82013-12-03 01:59:38 +0100267
268 On POSIX systems, the function sends SIGKILL to the subprocess.
269 On Windows, this method is an alias for :meth:`terminate`.
270
Victor Stinnerea3183f2013-12-03 01:08:00 +0100271 .. method:: send_signal(signal)
272
273 Send the *signal* number to the subprocess, as in
274 :meth:`subprocess.Popen.send_signal`.
275
276 .. method:: terminate()
277
278 Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`.
279 This method is an alias for the :meth:`close` method.
280
281 On POSIX systems, this method sends SIGTERM to the subprocess.
282 On Windows, the Windows API function TerminateProcess() is called to
283 stop the subprocess.
284
Victor Stinner4270a242014-10-13 23:56:43 +0200285 .. method:: close()
286
287 Ask the subprocess to stop by calling the :meth:`terminate` method if the
288 subprocess hasn't returned yet, and close transports of all pipes
289 (*stdin*, *stdout* and *stderr*).
290
Victor Stinnerea3183f2013-12-03 01:08:00 +0100291
Victor Stinner9592edb2014-02-02 15:03:02 +0100292.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100293
294Protocols
295=========
296
297:mod:`asyncio` provides base classes that you can subclass to implement
298your network protocols. Those classes are used in conjunction with
Victor Stinner9592edb2014-02-02 15:03:02 +0100299:ref:`transports <asyncio-transport>` (see below): the protocol parses incoming
Victor Stinnerea3183f2013-12-03 01:08:00 +0100300data and asks for the writing of outgoing data, while the transport is
301responsible for the actual I/O and buffering.
302
303When subclassing a protocol class, it is recommended you override certain
304methods. Those methods are callbacks: they will be called by the transport
305on certain events (for example when some data is received); you shouldn't
306call them yourself, unless you are implementing a transport.
307
308.. note::
309 All callbacks have default implementations, which are empty. Therefore,
310 you only need to implement the callbacks for the events in which you
311 are interested.
312
313
314Protocol classes
315----------------
316
317.. class:: Protocol
318
319 The base class for implementing streaming protocols (for use with
320 e.g. TCP and SSL transports).
321
322.. class:: DatagramProtocol
323
324 The base class for implementing datagram protocols (for use with
325 e.g. UDP transports).
326
327.. class:: SubprocessProtocol
328
329 The base class for implementing protocols communicating with child
330 processes (through a set of unidirectional pipes).
331
332
333Connection callbacks
334--------------------
335
Victor Stinner15386652014-06-10 09:19:26 +0200336These callbacks may be called on :class:`Protocol`, :class:`DatagramProtocol`
337and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100338
339.. method:: BaseProtocol.connection_made(transport)
340
341 Called when a connection is made.
342
343 The *transport* argument is the transport representing the
344 connection. You are responsible for storing it somewhere
345 (e.g. as an attribute) if you need to.
346
347.. method:: BaseProtocol.connection_lost(exc)
348
349 Called when the connection is lost or closed.
350
351 The argument is either an exception object or :const:`None`.
352 The latter means a regular EOF is received, or the connection was
353 aborted or closed by this side of the connection.
354
Victor Stinner15386652014-06-10 09:19:26 +0200355:meth:`~BaseProtocol.connection_made` and :meth:`~BaseProtocol.connection_lost`
356are called exactly once per successful connection. All other callbacks will be
357called between those two methods, which allows for easier resource management
358in your protocol implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100359
360The following callbacks may be called only on :class:`SubprocessProtocol`
361instances:
362
363.. method:: SubprocessProtocol.pipe_data_received(fd, data)
364
365 Called when the child process writes data into its stdout or stderr pipe.
366 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
367 bytes object containing the data.
368
369.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
370
371 Called when one of the pipes communicating with the child process
372 is closed. *fd* is the integer file descriptor that was closed.
373
374.. method:: SubprocessProtocol.process_exited()
375
376 Called when the child process has exited.
377
378
Victor Stinnerea3183f2013-12-03 01:08:00 +0100379Streaming protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100380-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100381
382The following callbacks are called on :class:`Protocol` instances:
383
384.. method:: Protocol.data_received(data)
385
386 Called when some data is received. *data* is a non-empty bytes object
387 containing the incoming data.
388
389 .. note::
390 Whether the data is buffered, chunked or reassembled depends on
391 the transport. In general, you shouldn't rely on specific semantics
392 and instead make your parsing generic and flexible enough. However,
393 data is always received in the correct order.
394
395.. method:: Protocol.eof_received()
396
Barry Warsawdd9a0a12017-04-07 14:18:14 -0400397 Called when the other end signals it won't send any more data
Victor Stinnerea3183f2013-12-03 01:08:00 +0100398 (for example by calling :meth:`write_eof`, if the other end also uses
399 asyncio).
400
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300401 This method may return a false value (including ``None``), in which case
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402 the transport will close itself. Conversely, if this method returns a
403 true value, closing the transport is up to the protocol. Since the
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300404 default implementation returns ``None``, it implicitly closes the connection.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100405
406 .. note::
407 Some transports such as SSL don't support half-closed connections,
408 in which case returning true from this method will not prevent closing
409 the connection.
410
411:meth:`data_received` can be called an arbitrary number of times during
412a connection. However, :meth:`eof_received` is called at most once
413and, if called, :meth:`data_received` won't be called after it.
414
Victor Stinner54a231d2015-01-29 13:33:15 +0100415State machine:
416
417 start -> :meth:`~BaseProtocol.connection_made`
418 [-> :meth:`~Protocol.data_received` \*]
419 [-> :meth:`~Protocol.eof_received` ?]
420 -> :meth:`~BaseProtocol.connection_lost` -> end
421
422
Victor Stinnerea3183f2013-12-03 01:08:00 +0100423Datagram protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100424------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100425
426The following callbacks are called on :class:`DatagramProtocol` instances.
427
428.. method:: DatagramProtocol.datagram_received(data, addr)
429
430 Called when a datagram is received. *data* is a bytes object containing
431 the incoming data. *addr* is the address of the peer sending the data;
432 the exact format depends on the transport.
433
434.. method:: DatagramProtocol.error_received(exc)
435
436 Called when a previous send or receive operation raises an
437 :class:`OSError`. *exc* is the :class:`OSError` instance.
438
439 This method is called in rare conditions, when the transport (e.g. UDP)
440 detects that a datagram couldn't be delivered to its recipient.
441 In many conditions though, undeliverable datagrams will be silently
442 dropped.
443
444
445Flow control callbacks
446----------------------
447
Larry Hastings3732ed22014-03-15 21:13:56 -0700448These callbacks may be called on :class:`Protocol`,
449:class:`DatagramProtocol` and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
451.. method:: BaseProtocol.pause_writing()
452
453 Called when the transport's buffer goes over the high-water mark.
454
455.. method:: BaseProtocol.resume_writing()
456
457 Called when the transport's buffer drains below the low-water mark.
458
459
460:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
461:meth:`pause_writing` is called once when the buffer goes strictly over
462the high-water mark (even if subsequent writes increases the buffer size
463even more), and eventually :meth:`resume_writing` is called once when the
464buffer size reaches the low-water mark.
465
466.. note::
467 If the buffer size equals the high-water mark,
468 :meth:`pause_writing` is not called -- it must go strictly over.
469 Conversely, :meth:`resume_writing` is called when the buffer size is
470 equal or lower than the low-water mark. These end conditions
471 are important to ensure that things go as expected when either
472 mark is zero.
473
Larry Hastings3732ed22014-03-15 21:13:56 -0700474.. note::
475 On BSD systems (OS X, FreeBSD, etc.) flow control is not supported
476 for :class:`DatagramProtocol`, because send failures caused by
477 writing too many packets cannot be detected easily. The socket
478 always appears 'ready' and excess packets are dropped; an
479 :class:`OSError` with errno set to :const:`errno.ENOBUFS` may or
480 may not be raised; if it is raised, it will be reported to
481 :meth:`DatagramProtocol.error_received` but otherwise ignored.
482
Victor Stinnerea3183f2013-12-03 01:08:00 +0100483
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100484Coroutines and protocols
485------------------------
486
Yury Selivanov04356e12015-06-30 22:13:22 -0400487Coroutines can be scheduled in a protocol method using :func:`ensure_future`,
488but there is no guarantee made about the execution order. Protocols are not
489aware of coroutines created in protocol methods and so will not wait for them.
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100490
Victor Stinner9592edb2014-02-02 15:03:02 +0100491To have a reliable execution order, use :ref:`stream objects <asyncio-streams>` in a
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100492coroutine with ``yield from``. For example, the :meth:`StreamWriter.drain`
493coroutine can be used to wait until the write buffer is flushed.
494
495
Victor Stinner04e6df32014-10-11 16:16:27 +0200496Protocol examples
497=================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100498
Victor Stinnered051592014-10-12 20:18:16 +0200499.. _asyncio-tcp-echo-client-protocol:
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100500
Victor Stinnered051592014-10-12 20:18:16 +0200501TCP echo client protocol
502------------------------
503
Guido van Rossumf68afd82016-08-08 09:41:21 -0700504TCP echo client using the :meth:`AbstractEventLoop.create_connection` method, send
Victor Stinnered051592014-10-12 20:18:16 +0200505data and wait until the connection is closed::
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100506
507 import asyncio
508
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200509 class EchoClientProtocol(asyncio.Protocol):
Victor Stinner53664342014-10-12 11:35:09 +0200510 def __init__(self, message, loop):
511 self.message = message
512 self.loop = loop
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100513
514 def connection_made(self, transport):
Victor Stinner31d83222013-12-04 11:16:17 +0100515 transport.write(self.message.encode())
Victor Stinner53664342014-10-12 11:35:09 +0200516 print('Data sent: {!r}'.format(self.message))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100517
518 def data_received(self, data):
Victor Stinner53664342014-10-12 11:35:09 +0200519 print('Data received: {!r}'.format(data.decode()))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100520
521 def connection_lost(self, exc):
Victor Stinner53664342014-10-12 11:35:09 +0200522 print('The server closed the connection')
Guido van Rossum41f69f42015-11-19 13:28:47 -0800523 print('Stop the event loop')
Victor Stinner53664342014-10-12 11:35:09 +0200524 self.loop.stop()
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100525
526 loop = asyncio.get_event_loop()
Victor Stinner53664342014-10-12 11:35:09 +0200527 message = 'Hello World!'
528 coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
529 '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100530 loop.run_until_complete(coro)
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100531 loop.run_forever()
532 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100533
Victor Stinnera881a7f2013-12-09 13:19:23 +0100534The event loop is running twice. The
Guido van Rossumf68afd82016-08-08 09:41:21 -0700535:meth:`~AbstractEventLoop.run_until_complete` method is preferred in this short
Victor Stinnera881a7f2013-12-09 13:19:23 +0100536example to raise an exception if the server is not listening, instead of
537having to write a short coroutine to handle the exception and stop the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700538running loop. At :meth:`~AbstractEventLoop.run_until_complete` exit, the loop is
Andrew Svetlov588517c2014-07-23 11:27:17 +0300539no longer running, so there is no need to stop the loop in case of an error.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100540
Victor Stinnered051592014-10-12 20:18:16 +0200541.. seealso::
Victor Stinnerc2721b42014-10-12 11:13:40 +0200542
Victor Stinnered051592014-10-12 20:18:16 +0200543 The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
544 example uses the :func:`asyncio.open_connection` function.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100545
Victor Stinnered051592014-10-12 20:18:16 +0200546
547.. _asyncio-tcp-echo-server-protocol:
548
549TCP echo server protocol
550------------------------
551
Guido van Rossumf68afd82016-08-08 09:41:21 -0700552TCP echo server using the :meth:`AbstractEventLoop.create_server` method, send back
Victor Stinnered051592014-10-12 20:18:16 +0200553received data and close the connection::
Victor Stinnera881a7f2013-12-09 13:19:23 +0100554
555 import asyncio
556
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200557 class EchoServerClientProtocol(asyncio.Protocol):
Victor Stinnera881a7f2013-12-09 13:19:23 +0100558 def connection_made(self, transport):
559 peername = transport.get_extra_info('peername')
Victor Stinnerc2721b42014-10-12 11:13:40 +0200560 print('Connection from {}'.format(peername))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100561 self.transport = transport
562
563 def data_received(self, data):
Victor Stinnerc2721b42014-10-12 11:13:40 +0200564 message = data.decode()
565 print('Data received: {!r}'.format(message))
566
567 print('Send: {!r}'.format(message))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100568 self.transport.write(data)
569
Victor Stinner53664342014-10-12 11:35:09 +0200570 print('Close the client socket')
Victor Stinnera881a7f2013-12-09 13:19:23 +0100571 self.transport.close()
572
573 loop = asyncio.get_event_loop()
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200574 # Each client connection will create a new protocol instance
575 coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100576 server = loop.run_until_complete(coro)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100577
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300578 # Serve requests until Ctrl+C is pressed
Victor Stinnerc2721b42014-10-12 11:13:40 +0200579 print('Serving on {}'.format(server.sockets[0].getsockname()))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100580 try:
581 loop.run_forever()
582 except KeyboardInterrupt:
Victor Stinnered051592014-10-12 20:18:16 +0200583 pass
Victor Stinnerc2721b42014-10-12 11:13:40 +0200584
585 # Close the server
586 server.close()
587 loop.run_until_complete(server.wait_closed())
588 loop.close()
Victor Stinnera881a7f2013-12-09 13:19:23 +0100589
R David Murray530a69f2013-12-14 11:26:06 -0500590:meth:`Transport.close` can be called immediately after
Victor Stinnera881a7f2013-12-09 13:19:23 +0100591:meth:`WriteTransport.write` even if data are not sent yet on the socket: both
592methods are asynchronous. ``yield from`` is not needed because these transport
Larry Hastings3732ed22014-03-15 21:13:56 -0700593methods are not coroutines.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100594
Victor Stinnered051592014-10-12 20:18:16 +0200595.. seealso::
596
597 The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>`
598 example uses the :func:`asyncio.start_server` function.
599
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200600
601.. _asyncio-udp-echo-client-protocol:
602
603UDP echo client protocol
604------------------------
605
Guido van Rossumf68afd82016-08-08 09:41:21 -0700606UDP echo client using the :meth:`AbstractEventLoop.create_datagram_endpoint`
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200607method, send data and close the transport when we received the answer::
608
609 import asyncio
610
611 class EchoClientProtocol:
612 def __init__(self, message, loop):
613 self.message = message
614 self.loop = loop
615 self.transport = None
616
617 def connection_made(self, transport):
618 self.transport = transport
619 print('Send:', self.message)
620 self.transport.sendto(self.message.encode())
621
622 def datagram_received(self, data, addr):
623 print("Received:", data.decode())
624
625 print("Close the socket")
626 self.transport.close()
627
628 def error_received(self, exc):
629 print('Error received:', exc)
630
631 def connection_lost(self, exc):
632 print("Socket closed, stop the event loop")
633 loop = asyncio.get_event_loop()
634 loop.stop()
635
636 loop = asyncio.get_event_loop()
637 message = "Hello World!"
638 connect = loop.create_datagram_endpoint(
639 lambda: EchoClientProtocol(message, loop),
640 remote_addr=('127.0.0.1', 9999))
641 transport, protocol = loop.run_until_complete(connect)
642 loop.run_forever()
643 transport.close()
644 loop.close()
645
646
647.. _asyncio-udp-echo-server-protocol:
648
649UDP echo server protocol
650------------------------
651
Guido van Rossumf68afd82016-08-08 09:41:21 -0700652UDP echo server using the :meth:`AbstractEventLoop.create_datagram_endpoint`
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200653method, send back received data::
654
655 import asyncio
656
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200657 class EchoServerProtocol:
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200658 def connection_made(self, transport):
659 self.transport = transport
660
661 def datagram_received(self, data, addr):
662 message = data.decode()
663 print('Received %r from %s' % (message, addr))
664 print('Send %r to %s' % (message, addr))
665 self.transport.sendto(data, addr)
666
667 loop = asyncio.get_event_loop()
668 print("Starting UDP server")
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200669 # One protocol instance will be created to serve all client requests
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200670 listen = loop.create_datagram_endpoint(
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200671 EchoServerProtocol, local_addr=('127.0.0.1', 9999))
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200672 transport, protocol = loop.run_until_complete(listen)
673
674 try:
675 loop.run_forever()
676 except KeyboardInterrupt:
677 pass
678
679 transport.close()
680 loop.close()
681
682
Victor Stinner04e6df32014-10-11 16:16:27 +0200683.. _asyncio-register-socket:
Victor Stinnera881a7f2013-12-09 13:19:23 +0100684
Victor Stinner04e6df32014-10-11 16:16:27 +0200685Register an open socket to wait for data using a protocol
686---------------------------------------------------------
687
688Wait until a socket receives data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700689:meth:`AbstractEventLoop.create_connection` method with a protocol, and then close
Victor Stinner04e6df32014-10-11 16:16:27 +0200690the event loop ::
691
692 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200693 try:
694 from socket import socketpair
695 except ImportError:
696 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200697
698 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200699 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200700 loop = asyncio.get_event_loop()
701
702 class MyProtocol(asyncio.Protocol):
703 transport = None
704
705 def connection_made(self, transport):
706 self.transport = transport
707
708 def data_received(self, data):
709 print("Received:", data.decode())
710
711 # We are done: close the transport (it will call connection_lost())
712 self.transport.close()
713
714 def connection_lost(self, exc):
715 # The socket has been closed, stop the event loop
716 loop.stop()
717
718 # Register the socket to wait for data
719 connect_coro = loop.create_connection(MyProtocol, sock=rsock)
720 transport, protocol = loop.run_until_complete(connect_coro)
721
722 # Simulate the reception of data from the network
723 loop.call_soon(wsock.send, 'abc'.encode())
724
725 # Run the event loop
726 loop.run_forever()
727
728 # We are done, close sockets and the event loop
729 rsock.close()
730 wsock.close()
731 loop.close()
732
733.. seealso::
734
735 The :ref:`watch a file descriptor for read events
736 <asyncio-watch-read-event>` example uses the low-level
Guido van Rossumf68afd82016-08-08 09:41:21 -0700737 :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a
Victor Stinner04e6df32014-10-11 16:16:27 +0200738 socket.
739
740 The :ref:`register an open socket to wait for data using streams
741 <asyncio-register-socket-streams>` example uses high-level streams
742 created by the :func:`open_connection` function in a coroutine.