blob: c0342f7f2f3ddcc5f363321452be1bc6d842df35 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanovcba00532015-12-16 21:30:52 -05003++++++++++++++++++++++++++++++++++++++++++++++
4Transports and protocols (callback based API)
5++++++++++++++++++++++++++++++++++++++++++++++
Victor Stinner1ca5ba62013-12-03 01:49:43 +01006
Victor Stinner9592edb2014-02-02 15:03:02 +01007.. _asyncio-transport:
Victor Stinnerea3183f2013-12-03 01:08:00 +01008
9Transports
10==========
11
Guido van Rossum589872c2014-03-29 21:14:04 -070012Transports are classes provided by :mod:`asyncio` in order to abstract
Victor Stinnerea3183f2013-12-03 01:08:00 +010013various kinds of communication channels. You generally won't instantiate
Martin Panterd210a702016-08-20 08:03:06 +000014a transport yourself; instead, you will call an :class:`AbstractEventLoop` method
Victor Stinnerea3183f2013-12-03 01:08:00 +010015which will create the transport and try to initiate the underlying
16communication channel, calling you back when it succeeds.
17
18Once the communication channel is established, a transport is always
Victor Stinner9592edb2014-02-02 15:03:02 +010019paired with a :ref:`protocol <asyncio-protocol>` instance. The protocol can
Victor Stinnerea3183f2013-12-03 01:08:00 +010020then call the transport's methods for various purposes.
21
22:mod:`asyncio` currently implements transports for TCP, UDP, SSL, and
23subprocess pipes. The methods available on a transport depend on
24the transport's kind.
25
Victor Stinner83704962015-02-25 14:24:15 +010026The transport classes are :ref:`not thread safe <asyncio-multithreading>`.
27
Victor Stinnerea3183f2013-12-03 01:08:00 +010028
Victor Stinner0c6f1ca2013-12-03 01:46:39 +010029BaseTransport
30-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
32.. class:: BaseTransport
33
34 Base class for transports.
35
36 .. method:: close(self)
37
38 Close the transport. If the transport has a buffer for outgoing
39 data, buffered data will be flushed asynchronously. No more data
40 will be received. After all buffered data is flushed, the
41 protocol's :meth:`connection_lost` method will be called with
42 :const:`None` as its argument.
43
Yury Selivanov1744d532015-11-16 12:46:41 -050044 .. method:: is_closing(self)
45
46 Return ``True`` if the transport is closing or is closed.
47
Yury Selivanov344904c2015-11-16 12:47:15 -050048 .. versionadded:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010049
50 .. method:: get_extra_info(name, default=None)
51
52 Return optional transport information. *name* is a string representing
53 the piece of transport-specific information to get, *default* is the
54 value to return if the information doesn't exist.
55
56 This method allows transport implementations to easily expose
57 channel-specific information.
58
59 * socket:
60
61 - ``'peername'``: the remote address to which the socket is connected,
62 result of :meth:`socket.socket.getpeername` (``None`` on error)
63 - ``'socket'``: :class:`socket.socket` instance
64 - ``'sockname'``: the socket's own address,
65 result of :meth:`socket.socket.getsockname`
66
67 * SSL socket:
68
69 - ``'compression'``: the compression algorithm being used as a string,
70 or ``None`` if the connection isn't compressed; result of
71 :meth:`ssl.SSLSocket.compression`
72 - ``'cipher'``: a three-value tuple containing the name of the cipher
73 being used, the version of the SSL protocol that defines its use, and
74 the number of secret bits being used; result of
75 :meth:`ssl.SSLSocket.cipher`
76 - ``'peercert'``: peer certificate; result of
77 :meth:`ssl.SSLSocket.getpeercert`
78 - ``'sslcontext'``: :class:`ssl.SSLContext` instance
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +020079 - ``'ssl_object'``: :class:`ssl.SSLObject` or :class:`ssl.SSLSocket`
80 instance
Victor Stinnerea3183f2013-12-03 01:08:00 +010081
82 * pipe:
83
84 - ``'pipe'``: pipe object
85
86 * subprocess:
87
88 - ``'subprocess'``: :class:`subprocess.Popen` instance
89
Berker Peksag2ebd6fe2016-11-07 23:36:14 +030090 .. method:: set_protocol(protocol)
INADA Naoki1ea023e2016-11-04 16:33:47 +090091
92 Set a new protocol. Switching protocol should only be done when both
93 protocols are documented to support the switch.
94
Berker Peksag2ebd6fe2016-11-07 23:36:14 +030095 .. versionadded:: 3.5.3
INADA Naoki1ea023e2016-11-04 16:33:47 +090096
Berker Peksag2ebd6fe2016-11-07 23:36:14 +030097 .. method:: get_protocol
INADA Naoki1ea023e2016-11-04 16:33:47 +090098
99 Return the current protocol.
100
Berker Peksag2ebd6fe2016-11-07 23:36:14 +0300101 .. versionadded:: 3.5.3
INADA Naoki1ea023e2016-11-04 16:33:47 +0900102
Victor Stinner04ce06b2015-09-21 18:27:52 +0200103 .. versionchanged:: 3.5.1
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +0200104 ``'ssl_object'`` info was added to SSL sockets.
105
Victor Stinnerea3183f2013-12-03 01:08:00 +0100106
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100107ReadTransport
108-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100109
110.. class:: ReadTransport
111
112 Interface for read-only transports.
113
114 .. method:: pause_reading()
115
116 Pause the receiving end of the transport. No data will be passed to
Victor Stinner51f31292014-03-21 17:17:15 +0100117 the protocol's :meth:`data_received` method until :meth:`resume_reading`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100118 is called.
119
120 .. method:: resume_reading()
121
122 Resume the receiving end. The protocol's :meth:`data_received` method
123 will be called once again if some data is available for reading.
124
125
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100126WriteTransport
127--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128
129.. class:: WriteTransport
130
131 Interface for write-only transports.
132
133 .. method:: abort()
134
135 Close the transport immediately, without waiting for pending operations
136 to complete. Buffered data will be lost. No more data will be received.
137 The protocol's :meth:`connection_lost` method will eventually be
138 called with :const:`None` as its argument.
139
140 .. method:: can_write_eof()
141
142 Return :const:`True` if the transport supports :meth:`write_eof`,
143 :const:`False` if not.
144
145 .. method:: get_write_buffer_size()
146
147 Return the current size of the output buffer used by the transport.
148
Victor Stinner52bb9492014-08-26 00:22:28 +0200149 .. method:: get_write_buffer_limits()
150
151 Get the *high*- and *low*-water limits for write flow control. Return a
152 tuple ``(low, high)`` where *low* and *high* are positive number of
153 bytes.
154
155 Use :meth:`set_write_buffer_limits` to set the limits.
156
157 .. versionadded:: 3.4.2
158
Victor Stinnerea3183f2013-12-03 01:08:00 +0100159 .. method:: set_write_buffer_limits(high=None, low=None)
160
161 Set the *high*- and *low*-water limits for write flow control.
162
163 These two values control when call the protocol's
164 :meth:`pause_writing` and :meth:`resume_writing` methods are called.
165 If specified, the low-water limit must be less than or equal to the
166 high-water limit. Neither *high* nor *low* can be negative.
167
168 The defaults are implementation-specific. If only the
Serhiy Storchakad65c9492015-11-02 14:10:23 +0200169 high-water limit is given, the low-water limit defaults to an
Victor Stinnerea3183f2013-12-03 01:08:00 +0100170 implementation-specific value less than or equal to the
171 high-water limit. Setting *high* to zero forces *low* to zero as
172 well, and causes :meth:`pause_writing` to be called whenever the
173 buffer becomes non-empty. Setting *low* to zero causes
174 :meth:`resume_writing` to be called only once the buffer is empty.
175 Use of zero for either limit is generally sub-optimal as it
176 reduces opportunities for doing I/O and computation
177 concurrently.
178
Victor Stinner52bb9492014-08-26 00:22:28 +0200179 Use :meth:`get_write_buffer_limits` to get the limits.
180
Victor Stinnerea3183f2013-12-03 01:08:00 +0100181 .. method:: write(data)
182
183 Write some *data* bytes to the transport.
184
185 This method does not block; it buffers the data and arranges for it
186 to be sent out asynchronously.
187
188 .. method:: writelines(list_of_data)
189
190 Write a list (or any iterable) of data bytes to the transport.
191 This is functionally equivalent to calling :meth:`write` on each
192 element yielded by the iterable, but may be implemented more efficiently.
193
194 .. method:: write_eof()
195
196 Close the write end of the transport after flushing buffered data.
197 Data may still be received.
198
199 This method can raise :exc:`NotImplementedError` if the transport
200 (e.g. SSL) doesn't support half-closes.
201
202
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100203DatagramTransport
204-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100205
206.. method:: DatagramTransport.sendto(data, addr=None)
207
208 Send the *data* bytes to the remote peer given by *addr* (a
209 transport-dependent target address). If *addr* is :const:`None`, the
210 data is sent to the target address given on transport creation.
211
212 This method does not block; it buffers the data and arranges for it
213 to be sent out asynchronously.
214
215.. method:: DatagramTransport.abort()
216
217 Close the transport immediately, without waiting for pending operations
218 to complete. Buffered data will be lost. No more data will be received.
219 The protocol's :meth:`connection_lost` method will eventually be
220 called with :const:`None` as its argument.
221
222
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100223BaseSubprocessTransport
224-----------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100225
226.. class:: BaseSubprocessTransport
227
228 .. method:: get_pid()
229
230 Return the subprocess process id as an integer.
231
Victor Stinnerea3183f2013-12-03 01:08:00 +0100232 .. method:: get_pipe_transport(fd)
233
Brian Curtina1afeec2014-02-08 18:36:14 -0600234 Return the transport for the communication pipe corresponding to the
Victor Stinner4270a242014-10-13 23:56:43 +0200235 integer file descriptor *fd*:
236
237 * ``0``: readable streaming transport of the standard input (*stdin*),
238 or :const:`None` if the subprocess was not created with ``stdin=PIPE``
239 * ``1``: writable streaming transport of the standard output (*stdout*),
240 or :const:`None` if the subprocess was not created with ``stdout=PIPE``
241 * ``2``: writable streaming transport of the standard error (*stderr*),
242 or :const:`None` if the subprocess was not created with ``stderr=PIPE``
243 * other *fd*: :const:`None`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100244
Victor Stinner933a8c82013-12-03 01:59:38 +0100245 .. method:: get_returncode()
246
247 Return the subprocess returncode as an integer or :const:`None`
248 if it hasn't returned, similarly to the
249 :attr:`subprocess.Popen.returncode` attribute.
250
251 .. method:: kill(self)
252
Martin Panterd21e0b52015-10-10 10:36:22 +0000253 Kill the subprocess, as in :meth:`subprocess.Popen.kill`.
Victor Stinner933a8c82013-12-03 01:59:38 +0100254
255 On POSIX systems, the function sends SIGKILL to the subprocess.
256 On Windows, this method is an alias for :meth:`terminate`.
257
Victor Stinnerea3183f2013-12-03 01:08:00 +0100258 .. method:: send_signal(signal)
259
260 Send the *signal* number to the subprocess, as in
261 :meth:`subprocess.Popen.send_signal`.
262
263 .. method:: terminate()
264
265 Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`.
266 This method is an alias for the :meth:`close` method.
267
268 On POSIX systems, this method sends SIGTERM to the subprocess.
269 On Windows, the Windows API function TerminateProcess() is called to
270 stop the subprocess.
271
Victor Stinner4270a242014-10-13 23:56:43 +0200272 .. method:: close()
273
274 Ask the subprocess to stop by calling the :meth:`terminate` method if the
275 subprocess hasn't returned yet, and close transports of all pipes
276 (*stdin*, *stdout* and *stderr*).
277
Victor Stinnerea3183f2013-12-03 01:08:00 +0100278
Victor Stinner9592edb2014-02-02 15:03:02 +0100279.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100280
281Protocols
282=========
283
284:mod:`asyncio` provides base classes that you can subclass to implement
285your network protocols. Those classes are used in conjunction with
Victor Stinner9592edb2014-02-02 15:03:02 +0100286:ref:`transports <asyncio-transport>` (see below): the protocol parses incoming
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287data and asks for the writing of outgoing data, while the transport is
288responsible for the actual I/O and buffering.
289
290When subclassing a protocol class, it is recommended you override certain
291methods. Those methods are callbacks: they will be called by the transport
292on certain events (for example when some data is received); you shouldn't
293call them yourself, unless you are implementing a transport.
294
295.. note::
296 All callbacks have default implementations, which are empty. Therefore,
297 you only need to implement the callbacks for the events in which you
298 are interested.
299
300
301Protocol classes
302----------------
303
304.. class:: Protocol
305
306 The base class for implementing streaming protocols (for use with
307 e.g. TCP and SSL transports).
308
309.. class:: DatagramProtocol
310
311 The base class for implementing datagram protocols (for use with
312 e.g. UDP transports).
313
314.. class:: SubprocessProtocol
315
316 The base class for implementing protocols communicating with child
317 processes (through a set of unidirectional pipes).
318
319
320Connection callbacks
321--------------------
322
Victor Stinner15386652014-06-10 09:19:26 +0200323These callbacks may be called on :class:`Protocol`, :class:`DatagramProtocol`
324and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100325
326.. method:: BaseProtocol.connection_made(transport)
327
328 Called when a connection is made.
329
330 The *transport* argument is the transport representing the
331 connection. You are responsible for storing it somewhere
332 (e.g. as an attribute) if you need to.
333
334.. method:: BaseProtocol.connection_lost(exc)
335
336 Called when the connection is lost or closed.
337
338 The argument is either an exception object or :const:`None`.
339 The latter means a regular EOF is received, or the connection was
340 aborted or closed by this side of the connection.
341
Victor Stinner15386652014-06-10 09:19:26 +0200342:meth:`~BaseProtocol.connection_made` and :meth:`~BaseProtocol.connection_lost`
343are called exactly once per successful connection. All other callbacks will be
344called between those two methods, which allows for easier resource management
345in your protocol implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100346
347The following callbacks may be called only on :class:`SubprocessProtocol`
348instances:
349
350.. method:: SubprocessProtocol.pipe_data_received(fd, data)
351
352 Called when the child process writes data into its stdout or stderr pipe.
353 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
354 bytes object containing the data.
355
356.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
357
358 Called when one of the pipes communicating with the child process
359 is closed. *fd* is the integer file descriptor that was closed.
360
361.. method:: SubprocessProtocol.process_exited()
362
363 Called when the child process has exited.
364
365
Victor Stinnerea3183f2013-12-03 01:08:00 +0100366Streaming protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100367-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100368
369The following callbacks are called on :class:`Protocol` instances:
370
371.. method:: Protocol.data_received(data)
372
373 Called when some data is received. *data* is a non-empty bytes object
374 containing the incoming data.
375
376 .. note::
377 Whether the data is buffered, chunked or reassembled depends on
378 the transport. In general, you shouldn't rely on specific semantics
379 and instead make your parsing generic and flexible enough. However,
380 data is always received in the correct order.
381
382.. method:: Protocol.eof_received()
383
384 Calls when the other end signals it won't send any more data
385 (for example by calling :meth:`write_eof`, if the other end also uses
386 asyncio).
387
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300388 This method may return a false value (including ``None``), in which case
Victor Stinnerea3183f2013-12-03 01:08:00 +0100389 the transport will close itself. Conversely, if this method returns a
390 true value, closing the transport is up to the protocol. Since the
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300391 default implementation returns ``None``, it implicitly closes the connection.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
393 .. note::
394 Some transports such as SSL don't support half-closed connections,
395 in which case returning true from this method will not prevent closing
396 the connection.
397
398:meth:`data_received` can be called an arbitrary number of times during
399a connection. However, :meth:`eof_received` is called at most once
400and, if called, :meth:`data_received` won't be called after it.
401
Victor Stinner54a231d2015-01-29 13:33:15 +0100402State machine:
403
404 start -> :meth:`~BaseProtocol.connection_made`
405 [-> :meth:`~Protocol.data_received` \*]
406 [-> :meth:`~Protocol.eof_received` ?]
407 -> :meth:`~BaseProtocol.connection_lost` -> end
408
409
Victor Stinnerea3183f2013-12-03 01:08:00 +0100410Datagram protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100411------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100412
413The following callbacks are called on :class:`DatagramProtocol` instances.
414
415.. method:: DatagramProtocol.datagram_received(data, addr)
416
417 Called when a datagram is received. *data* is a bytes object containing
418 the incoming data. *addr* is the address of the peer sending the data;
419 the exact format depends on the transport.
420
421.. method:: DatagramProtocol.error_received(exc)
422
423 Called when a previous send or receive operation raises an
424 :class:`OSError`. *exc* is the :class:`OSError` instance.
425
426 This method is called in rare conditions, when the transport (e.g. UDP)
427 detects that a datagram couldn't be delivered to its recipient.
428 In many conditions though, undeliverable datagrams will be silently
429 dropped.
430
431
432Flow control callbacks
433----------------------
434
Larry Hastings3732ed22014-03-15 21:13:56 -0700435These callbacks may be called on :class:`Protocol`,
436:class:`DatagramProtocol` and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
438.. method:: BaseProtocol.pause_writing()
439
440 Called when the transport's buffer goes over the high-water mark.
441
442.. method:: BaseProtocol.resume_writing()
443
444 Called when the transport's buffer drains below the low-water mark.
445
446
447:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
448:meth:`pause_writing` is called once when the buffer goes strictly over
449the high-water mark (even if subsequent writes increases the buffer size
450even more), and eventually :meth:`resume_writing` is called once when the
451buffer size reaches the low-water mark.
452
453.. note::
454 If the buffer size equals the high-water mark,
455 :meth:`pause_writing` is not called -- it must go strictly over.
456 Conversely, :meth:`resume_writing` is called when the buffer size is
457 equal or lower than the low-water mark. These end conditions
458 are important to ensure that things go as expected when either
459 mark is zero.
460
Larry Hastings3732ed22014-03-15 21:13:56 -0700461.. note::
462 On BSD systems (OS X, FreeBSD, etc.) flow control is not supported
463 for :class:`DatagramProtocol`, because send failures caused by
464 writing too many packets cannot be detected easily. The socket
465 always appears 'ready' and excess packets are dropped; an
466 :class:`OSError` with errno set to :const:`errno.ENOBUFS` may or
467 may not be raised; if it is raised, it will be reported to
468 :meth:`DatagramProtocol.error_received` but otherwise ignored.
469
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100471Coroutines and protocols
472------------------------
473
Yury Selivanov04356e12015-06-30 22:13:22 -0400474Coroutines can be scheduled in a protocol method using :func:`ensure_future`,
475but there is no guarantee made about the execution order. Protocols are not
476aware of coroutines created in protocol methods and so will not wait for them.
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100477
Victor Stinner9592edb2014-02-02 15:03:02 +0100478To have a reliable execution order, use :ref:`stream objects <asyncio-streams>` in a
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100479coroutine with ``yield from``. For example, the :meth:`StreamWriter.drain`
480coroutine can be used to wait until the write buffer is flushed.
481
482
Victor Stinner04e6df32014-10-11 16:16:27 +0200483Protocol examples
484=================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100485
Victor Stinnered051592014-10-12 20:18:16 +0200486.. _asyncio-tcp-echo-client-protocol:
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100487
Victor Stinnered051592014-10-12 20:18:16 +0200488TCP echo client protocol
489------------------------
490
Guido van Rossumf68afd82016-08-08 09:41:21 -0700491TCP echo client using the :meth:`AbstractEventLoop.create_connection` method, send
Victor Stinnered051592014-10-12 20:18:16 +0200492data and wait until the connection is closed::
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100493
494 import asyncio
495
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200496 class EchoClientProtocol(asyncio.Protocol):
Victor Stinner53664342014-10-12 11:35:09 +0200497 def __init__(self, message, loop):
498 self.message = message
499 self.loop = loop
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100500
501 def connection_made(self, transport):
Victor Stinner31d83222013-12-04 11:16:17 +0100502 transport.write(self.message.encode())
Victor Stinner53664342014-10-12 11:35:09 +0200503 print('Data sent: {!r}'.format(self.message))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100504
505 def data_received(self, data):
Victor Stinner53664342014-10-12 11:35:09 +0200506 print('Data received: {!r}'.format(data.decode()))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100507
508 def connection_lost(self, exc):
Victor Stinner53664342014-10-12 11:35:09 +0200509 print('The server closed the connection')
Guido van Rossum41f69f42015-11-19 13:28:47 -0800510 print('Stop the event loop')
Victor Stinner53664342014-10-12 11:35:09 +0200511 self.loop.stop()
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100512
513 loop = asyncio.get_event_loop()
Victor Stinner53664342014-10-12 11:35:09 +0200514 message = 'Hello World!'
515 coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
516 '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100517 loop.run_until_complete(coro)
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100518 loop.run_forever()
519 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100520
Victor Stinnera881a7f2013-12-09 13:19:23 +0100521The event loop is running twice. The
Guido van Rossumf68afd82016-08-08 09:41:21 -0700522:meth:`~AbstractEventLoop.run_until_complete` method is preferred in this short
Victor Stinnera881a7f2013-12-09 13:19:23 +0100523example to raise an exception if the server is not listening, instead of
524having to write a short coroutine to handle the exception and stop the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700525running loop. At :meth:`~AbstractEventLoop.run_until_complete` exit, the loop is
Andrew Svetlov588517c2014-07-23 11:27:17 +0300526no longer running, so there is no need to stop the loop in case of an error.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100527
Victor Stinnered051592014-10-12 20:18:16 +0200528.. seealso::
Victor Stinnerc2721b42014-10-12 11:13:40 +0200529
Victor Stinnered051592014-10-12 20:18:16 +0200530 The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
531 example uses the :func:`asyncio.open_connection` function.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100532
Victor Stinnered051592014-10-12 20:18:16 +0200533
534.. _asyncio-tcp-echo-server-protocol:
535
536TCP echo server protocol
537------------------------
538
Guido van Rossumf68afd82016-08-08 09:41:21 -0700539TCP echo server using the :meth:`AbstractEventLoop.create_server` method, send back
Victor Stinnered051592014-10-12 20:18:16 +0200540received data and close the connection::
Victor Stinnera881a7f2013-12-09 13:19:23 +0100541
542 import asyncio
543
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200544 class EchoServerClientProtocol(asyncio.Protocol):
Victor Stinnera881a7f2013-12-09 13:19:23 +0100545 def connection_made(self, transport):
546 peername = transport.get_extra_info('peername')
Victor Stinnerc2721b42014-10-12 11:13:40 +0200547 print('Connection from {}'.format(peername))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100548 self.transport = transport
549
550 def data_received(self, data):
Victor Stinnerc2721b42014-10-12 11:13:40 +0200551 message = data.decode()
552 print('Data received: {!r}'.format(message))
553
554 print('Send: {!r}'.format(message))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100555 self.transport.write(data)
556
Victor Stinner53664342014-10-12 11:35:09 +0200557 print('Close the client socket')
Victor Stinnera881a7f2013-12-09 13:19:23 +0100558 self.transport.close()
559
560 loop = asyncio.get_event_loop()
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200561 # Each client connection will create a new protocol instance
562 coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100563 server = loop.run_until_complete(coro)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100564
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300565 # Serve requests until Ctrl+C is pressed
Victor Stinnerc2721b42014-10-12 11:13:40 +0200566 print('Serving on {}'.format(server.sockets[0].getsockname()))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100567 try:
568 loop.run_forever()
569 except KeyboardInterrupt:
Victor Stinnered051592014-10-12 20:18:16 +0200570 pass
Victor Stinnerc2721b42014-10-12 11:13:40 +0200571
572 # Close the server
573 server.close()
574 loop.run_until_complete(server.wait_closed())
575 loop.close()
Victor Stinnera881a7f2013-12-09 13:19:23 +0100576
R David Murray530a69f2013-12-14 11:26:06 -0500577:meth:`Transport.close` can be called immediately after
Victor Stinnera881a7f2013-12-09 13:19:23 +0100578:meth:`WriteTransport.write` even if data are not sent yet on the socket: both
579methods are asynchronous. ``yield from`` is not needed because these transport
Larry Hastings3732ed22014-03-15 21:13:56 -0700580methods are not coroutines.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100581
Victor Stinnered051592014-10-12 20:18:16 +0200582.. seealso::
583
584 The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>`
585 example uses the :func:`asyncio.start_server` function.
586
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200587
588.. _asyncio-udp-echo-client-protocol:
589
590UDP echo client protocol
591------------------------
592
Guido van Rossumf68afd82016-08-08 09:41:21 -0700593UDP echo client using the :meth:`AbstractEventLoop.create_datagram_endpoint`
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200594method, send data and close the transport when we received the answer::
595
596 import asyncio
597
598 class EchoClientProtocol:
599 def __init__(self, message, loop):
600 self.message = message
601 self.loop = loop
602 self.transport = None
603
604 def connection_made(self, transport):
605 self.transport = transport
606 print('Send:', self.message)
607 self.transport.sendto(self.message.encode())
608
609 def datagram_received(self, data, addr):
610 print("Received:", data.decode())
611
612 print("Close the socket")
613 self.transport.close()
614
615 def error_received(self, exc):
616 print('Error received:', exc)
617
618 def connection_lost(self, exc):
619 print("Socket closed, stop the event loop")
620 loop = asyncio.get_event_loop()
621 loop.stop()
622
623 loop = asyncio.get_event_loop()
624 message = "Hello World!"
625 connect = loop.create_datagram_endpoint(
626 lambda: EchoClientProtocol(message, loop),
627 remote_addr=('127.0.0.1', 9999))
628 transport, protocol = loop.run_until_complete(connect)
629 loop.run_forever()
630 transport.close()
631 loop.close()
632
633
634.. _asyncio-udp-echo-server-protocol:
635
636UDP echo server protocol
637------------------------
638
Guido van Rossumf68afd82016-08-08 09:41:21 -0700639UDP echo server using the :meth:`AbstractEventLoop.create_datagram_endpoint`
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200640method, send back received data::
641
642 import asyncio
643
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200644 class EchoServerProtocol:
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200645 def connection_made(self, transport):
646 self.transport = transport
647
648 def datagram_received(self, data, addr):
649 message = data.decode()
650 print('Received %r from %s' % (message, addr))
651 print('Send %r to %s' % (message, addr))
652 self.transport.sendto(data, addr)
653
654 loop = asyncio.get_event_loop()
655 print("Starting UDP server")
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200656 # One protocol instance will be created to serve all client requests
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200657 listen = loop.create_datagram_endpoint(
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200658 EchoServerProtocol, local_addr=('127.0.0.1', 9999))
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200659 transport, protocol = loop.run_until_complete(listen)
660
661 try:
662 loop.run_forever()
663 except KeyboardInterrupt:
664 pass
665
666 transport.close()
667 loop.close()
668
669
Victor Stinner04e6df32014-10-11 16:16:27 +0200670.. _asyncio-register-socket:
Victor Stinnera881a7f2013-12-09 13:19:23 +0100671
Victor Stinner04e6df32014-10-11 16:16:27 +0200672Register an open socket to wait for data using a protocol
673---------------------------------------------------------
674
675Wait until a socket receives data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700676:meth:`AbstractEventLoop.create_connection` method with a protocol, and then close
Victor Stinner04e6df32014-10-11 16:16:27 +0200677the event loop ::
678
679 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200680 try:
681 from socket import socketpair
682 except ImportError:
683 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200684
685 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200686 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200687 loop = asyncio.get_event_loop()
688
689 class MyProtocol(asyncio.Protocol):
690 transport = None
691
692 def connection_made(self, transport):
693 self.transport = transport
694
695 def data_received(self, data):
696 print("Received:", data.decode())
697
698 # We are done: close the transport (it will call connection_lost())
699 self.transport.close()
700
701 def connection_lost(self, exc):
702 # The socket has been closed, stop the event loop
703 loop.stop()
704
705 # Register the socket to wait for data
706 connect_coro = loop.create_connection(MyProtocol, sock=rsock)
707 transport, protocol = loop.run_until_complete(connect_coro)
708
709 # Simulate the reception of data from the network
710 loop.call_soon(wsock.send, 'abc'.encode())
711
712 # Run the event loop
713 loop.run_forever()
714
715 # We are done, close sockets and the event loop
716 rsock.close()
717 wsock.close()
718 loop.close()
719
720.. seealso::
721
722 The :ref:`watch a file descriptor for read events
723 <asyncio-watch-read-event>` example uses the low-level
Guido van Rossumf68afd82016-08-08 09:41:21 -0700724 :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a
Victor Stinner04e6df32014-10-11 16:16:27 +0200725 socket.
726
727 The :ref:`register an open socket to wait for data using streams
728 <asyncio-register-socket-streams>` example uses high-level streams
729 created by the :func:`open_connection` function in a coroutine.