blob: 28ca5d5f339692ff9b9e7dcd049a989d853b5301 [file] [log] [blame]
Victor Stinner24f8ebf2014-01-23 11:05:01 +01001.. currentmodule:: asyncio
2
Victor Stinner9592edb2014-02-02 15:03:02 +01003.. _asyncio-streams:
Victor Stinner4b4f9eb2014-01-24 17:33:20 +01004
Yury Selivanov7c7605f2018-09-11 09:54:40 -07005=======
6Streams
7=======
Victor Stinner24f8ebf2014-01-23 11:05:01 +01008
Yury Selivanov7c7605f2018-09-11 09:54:40 -07009Streams are high-level async/await-ready primitives to work with
Yury Selivanov8be876e2018-09-11 17:10:37 -070010network connections. Streams allow sending and receiving data without
Yury Selivanov7c7605f2018-09-11 09:54:40 -070011using callbacks or low-level protocols and transports.
lf627d2c82017-07-25 17:03:51 -060012
Yury Selivanov7372c3b2018-09-14 15:11:24 -070013.. _asyncio_example_stream:
14
Yury Selivanov8be876e2018-09-11 17:10:37 -070015Here is an example of a TCP echo client written using asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -070016streams::
Victor Stinner24f8ebf2014-01-23 11:05:01 +010017
Yury Selivanov7c7605f2018-09-11 09:54:40 -070018 import asyncio
Guido van Rossum19ff6972015-10-19 13:18:04 -070019
Yury Selivanov7c7605f2018-09-11 09:54:40 -070020 async def tcp_echo_client(message):
21 reader, writer = await asyncio.open_connection(
22 '127.0.0.1', 8888)
23
24 print(f'Send: {message!r}')
Andrew Svetlova076e4f2019-05-09 15:14:58 -040025 await writer.write(message.encode())
Yury Selivanov7c7605f2018-09-11 09:54:40 -070026
27 data = await reader.read(100)
28 print(f'Received: {data.decode()!r}')
29
30 print('Close the connection')
Andrew Svetlova076e4f2019-05-09 15:14:58 -040031 await writer.close()
Yury Selivanov7c7605f2018-09-11 09:54:40 -070032
33 asyncio.run(tcp_echo_client('Hello World!'))
Guido van Rossum19ff6972015-10-19 13:18:04 -070034
35
Yury Selivanov8be876e2018-09-11 17:10:37 -070036See also the `Examples`_ section below.
37
38
Yury Selivanov7c7605f2018-09-11 09:54:40 -070039.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010040
Yury Selivanov7c7605f2018-09-11 09:54:40 -070041The following top-level asyncio functions can be used to create
42and work with streams:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010043
Victor Stinner24f8ebf2014-01-23 11:05:01 +010044
Yury Selivanov7c7605f2018-09-11 09:54:40 -070045.. coroutinefunction:: open_connection(host=None, port=None, \*, \
46 loop=None, limit=None, ssl=None, family=0, \
47 proto=0, flags=0, sock=None, local_addr=None, \
48 server_hostname=None, ssl_handshake_timeout=None)
49
50 Establish a network connection and return a pair of
Yury Selivanov8be876e2018-09-11 17:10:37 -070051 ``(reader, writer)`` objects.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070052
53 The returned *reader* and *writer* objects are instances of
54 :class:`StreamReader` and :class:`StreamWriter` classes.
55
56 The *loop* argument is optional and can always be determined
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040057 automatically when this function is awaited from a coroutine.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070058
59 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070060 returned :class:`StreamReader` instance. By default the *limit*
61 is set to 64 KiB.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010062
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040063 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070064 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010065
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040066 .. versionadded:: 3.7
67
68 The *ssl_handshake_timeout* parameter.
69
Emmanuel Ariased9f3562019-05-31 17:48:57 -030070 .. deprecated-removed:: 3.8 3.10
71
72 `open_connection()` is deprecated in favor of `connect()`.
73
Yury Selivanov7c7605f2018-09-11 09:54:40 -070074.. coroutinefunction:: start_server(client_connected_cb, host=None, \
75 port=None, \*, loop=None, limit=None, \
76 family=socket.AF_UNSPEC, \
77 flags=socket.AI_PASSIVE, sock=None, \
78 backlog=100, ssl=None, reuse_address=None, \
79 reuse_port=None, ssl_handshake_timeout=None, \
80 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010081
Yury Selivanov7c7605f2018-09-11 09:54:40 -070082 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010083
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040084 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070085 connection is established. It receives a ``(reader, writer)`` pair
86 as two arguments, instances of the :class:`StreamReader` and
87 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010088
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040090 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040091 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010092
Yury Selivanov7c7605f2018-09-11 09:54:40 -070093 The *loop* argument is optional and can always be determined
94 automatically when this method is awaited from a coroutine.
95
96 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070097 returned :class:`StreamReader` instance. By default the *limit*
98 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040099
100 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700101 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100102
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400103 .. versionadded:: 3.7
104
105 The *ssl_handshake_timeout* and *start_serving* parameters.
106
Emmanuel Ariased9f3562019-05-31 17:48:57 -0300107 .. deprecated-removed:: 3.8 3.10
108
109 `start_server()` is deprecated if favor of `StreamServer()`
110
Yury Selivanov8be876e2018-09-11 17:10:37 -0700111
112.. rubric:: Unix Sockets
113
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700114.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
115 limit=None, ssl=None, sock=None, \
116 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500117
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400118 Establish a Unix socket connection and return a pair of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700119 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500120
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400121 Similar to :func:`open_connection` but operates on Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400122
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700123 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500124
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400125 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500126
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400127 .. versionadded:: 3.7
128
129 The *ssl_handshake_timeout* parameter.
130
131 .. versionchanged:: 3.7
132
133 The *path* parameter can now be a :term:`path-like object`
134
Emmanuel Ariased9f3562019-05-31 17:48:57 -0300135 .. deprecated-removed:: 3.8 3.10
136
137 `open_unix_connection()` is deprecated if favor of `connect_unix()`.
138
Yury Selivanov8be876e2018-09-11 17:10:37 -0700139
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700140.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
141 \*, loop=None, limit=None, sock=None, \
142 backlog=100, ssl=None, ssl_handshake_timeout=None, \
143 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500144
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400145 Start a Unix socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500146
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400147 Similar to :func:`start_server` but works with Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400148
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700149 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500150
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400151 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500152
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400153 .. versionadded:: 3.7
154
155 The *ssl_handshake_timeout* and *start_serving* parameters.
156
157 .. versionchanged:: 3.7
158
159 The *path* parameter can now be a :term:`path-like object`.
160
Emmanuel Ariased9f3562019-05-31 17:48:57 -0300161 .. deprecated-removed:: 3.8 3.10
162
163 `start_unix_server()` is deprecated in favor of `UnixStreamServer()`.
164
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
Yury Selivanov8be876e2018-09-11 17:10:37 -0700166---------
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700167
168
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100169StreamReader
170============
171
Yury Selivanov8be876e2018-09-11 17:10:37 -0700172.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100173
Yury Selivanov8be876e2018-09-11 17:10:37 -0700174 Represents a reader object that provides APIs to read data
175 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100176
Yury Selivanov8be876e2018-09-11 17:10:37 -0700177 It is not recommended to instantiate *StreamReader* objects
178 directly; use :func:`open_connection` and :func:`start_server`
179 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100180
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100181 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100182
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500183 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
184 read until EOF and return all read bytes.
185
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400186 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500187 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100188
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100189 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100190
Yury Selivanov8be876e2018-09-11 17:10:37 -0700191 Read one line, where "line" is a sequence of bytes
192 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500193
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400194 If EOF is received and ``\n`` was not found, the method
Yury Selivanov8be876e2018-09-11 17:10:37 -0700195 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500196
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400197 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500198 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100199
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100200 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100201
Yury Selivanov8be876e2018-09-11 17:10:37 -0700202 Read exactly *n* bytes.
203
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400204 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
Yury Selivanov8be876e2018-09-11 17:10:37 -0700205 can be read. Use the :attr:`IncompleteReadError.partial`
206 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100207
Berker Peksage5b0bd12016-10-18 00:34:46 +0300208 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400209
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400210 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400211
212 On success, the data and separator will be removed from the
213 internal buffer (consumed). Returned data will include the
214 separator at the end.
215
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400216 If the amount of data read exceeds the configured stream limit, a
217 :exc:`LimitOverrunError` exception is raised, and the data
218 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400219
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400220 If EOF is reached before the complete separator is found,
221 an :exc:`IncompleteReadError` exception is raised, and the internal
222 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
223 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400224
225 .. versionadded:: 3.5.2
226
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500227 .. method:: at_eof()
228
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700229 Return ``True`` if the buffer is empty and :meth:`feed_eof`
230 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500231
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100232
233StreamWriter
234============
235
Yury Selivanov8be876e2018-09-11 17:10:37 -0700236.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100237
Yury Selivanov8be876e2018-09-11 17:10:37 -0700238 Represents a writer object that provides APIs to write data
239 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100240
Yury Selivanov8be876e2018-09-11 17:10:37 -0700241 It is not recommended to instantiate *StreamWriter* objects
242 directly; use :func:`open_connection` and :func:`start_server`
243 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100244
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400245 .. method:: write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700246
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400247 The method attempts to write the *data* to the underlying socket immediately.
248 If that fails, the data is queued in an internal write buffer until it can be
249 sent.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700250
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400251 Starting with Python 3.8, it is possible to directly await on the `write()`
252 method::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700253
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400254 await stream.write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700255
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400256 The ``await`` pauses the current coroutine until the data is written to the
257 socket.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700258
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400259 Below is an equivalent code that works with Python <= 3.7::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700260
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400261 stream.write(data)
262 await stream.drain()
Andrew Svetlov11194c82018-09-13 16:53:49 -0700263
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400264 .. versionchanged:: 3.8
265 Support ``await stream.write(...)`` syntax.
266
267 .. method:: writelines(data)
268
269 The method writes a list (or any iterable) of bytes to the underlying socket
270 immediately.
271 If that fails, the data is queued in an internal write buffer until it can be
272 sent.
273
274 Starting with Python 3.8, it is possible to directly await on the `write()`
275 method::
276
277 await stream.writelines(lines)
278
279 The ``await`` pauses the current coroutine until the data is written to the
280 socket.
281
282 Below is an equivalent code that works with Python <= 3.7::
283
284 stream.writelines(lines)
285 await stream.drain()
286
287 .. versionchanged:: 3.8
288 Support ``await stream.writelines()`` syntax.
289
290 .. method:: close()
291
292 The method closes the stream and the underlying socket.
293
294 Starting with Python 3.8, it is possible to directly await on the `close()`
295 method::
296
297 await stream.close()
298
299 The ``await`` pauses the current coroutine until the stream and the underlying
300 socket are closed (and SSL shutdown is performed for a secure connection).
301
302 Below is an equivalent code that works with Python <= 3.7::
303
304 stream.close()
305 await stream.wait_closed()
306
307 .. versionchanged:: 3.8
308 Support ``await stream.close()`` syntax.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700309
310 .. method:: can_write_eof()
311
312 Return *True* if the underlying transport supports
313 the :meth:`write_eof` method, *False* otherwise.
314
315 .. method:: write_eof()
316
317 Close the write end of the stream after the buffered write
318 data is flushed.
319
320 .. attribute:: transport
321
322 Return the underlying asyncio transport.
323
324 .. method:: get_extra_info(name, default=None)
325
326 Access optional transport information; see
327 :meth:`BaseTransport.get_extra_info` for details.
328
Yury Selivanov8be876e2018-09-11 17:10:37 -0700329 .. coroutinemethod:: drain()
330
331 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400332 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700333
334 writer.write(data)
335 await writer.drain()
336
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400337 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700338 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400339 the high watermark, *drain()* blocks until the size of the
340 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700341 be resumed. When there is nothing to wait for, the :meth:`drain`
342 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100343
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200344 .. method:: is_closing()
345
Yury Selivanov8be876e2018-09-11 17:10:37 -0700346 Return ``True`` if the stream is closed or in the process of
347 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200348
349 .. versionadded:: 3.7
350
351 .. coroutinemethod:: wait_closed()
352
Yury Selivanov8be876e2018-09-11 17:10:37 -0700353 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200354
Yury Selivanov8be876e2018-09-11 17:10:37 -0700355 Should be called after :meth:`close` to wait until the underlying
356 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200357
358 .. versionadded:: 3.7
359
Victor Stinnerc520edc2014-01-23 11:25:48 +0100360
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700361Examples
362========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200363
Victor Stinnered051592014-10-12 20:18:16 +0200364.. _asyncio-tcp-echo-client-streams:
365
366TCP echo client using streams
367-----------------------------
368
369TCP echo client using the :func:`asyncio.open_connection` function::
370
371 import asyncio
372
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700373 async def tcp_echo_client(message):
374 reader, writer = await asyncio.open_connection(
375 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200376
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700377 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200378 writer.write(message.encode())
379
Andrew Svetlov88743422017-12-11 17:35:49 +0200380 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700381 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200382
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700383 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200384 writer.close()
385
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700386 asyncio.run(tcp_echo_client('Hello World!'))
387
Victor Stinnered051592014-10-12 20:18:16 +0200388
389.. seealso::
390
Yury Selivanov394374e2018-09-17 15:35:24 -0400391 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700392 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200393
394
395.. _asyncio-tcp-echo-server-streams:
396
397TCP echo server using streams
398-----------------------------
399
400TCP echo server using the :func:`asyncio.start_server` function::
401
402 import asyncio
403
Andrew Svetlov88743422017-12-11 17:35:49 +0200404 async def handle_echo(reader, writer):
405 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200406 message = data.decode()
407 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200408
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700409 print(f"Received {message!r} from {addr!r}")
410
411 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200412 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200413 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200414
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700415 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200416 writer.close()
417
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700418 async def main():
419 server = await asyncio.start_server(
420 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200421
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700422 addr = server.sockets[0].getsockname()
423 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200424
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700425 async with server:
426 await server.serve_forever()
427
428 asyncio.run(main())
429
Victor Stinnered051592014-10-12 20:18:16 +0200430
431.. seealso::
432
Yury Selivanov394374e2018-09-17 15:35:24 -0400433 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700434 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200435
436
Victor Stinner5121a9b2014-10-11 15:52:14 +0200437Get HTTP headers
438----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100439
440Simple example querying HTTP headers of the URL passed on the command line::
441
442 import asyncio
443 import urllib.parse
444 import sys
445
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400446 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100447 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200448 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700449 reader, writer = await asyncio.open_connection(
450 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200451 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700452 reader, writer = await asyncio.open_connection(
453 url.hostname, 80)
454
455 query = (
456 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
457 f"Host: {url.hostname}\r\n"
458 f"\r\n"
459 )
460
Victor Stinnerc520edc2014-01-23 11:25:48 +0100461 writer.write(query.encode('latin-1'))
462 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200463 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100464 if not line:
465 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700466
Victor Stinnerc520edc2014-01-23 11:25:48 +0100467 line = line.decode('latin1').rstrip()
468 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700469 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100470
Victor Stinner5121a9b2014-10-11 15:52:14 +0200471 # Ignore the body, close the socket
472 writer.close()
473
Victor Stinnerc520edc2014-01-23 11:25:48 +0100474 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700475 asyncio.run(print_http_headers(url))
476
Victor Stinnerc520edc2014-01-23 11:25:48 +0100477
478Usage::
479
480 python example.py http://example.com/path/page.html
481
Victor Stinner04e6df32014-10-11 16:16:27 +0200482or with HTTPS::
483
484 python example.py https://example.com/path/page.html
485
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700486
Yury Selivanov394374e2018-09-17 15:35:24 -0400487.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200488
489Register an open socket to wait for data using streams
490------------------------------------------------------
491
492Coroutine waiting until a socket receives data using the
493:func:`open_connection` function::
494
495 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700496 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200497
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700498 async def wait_for_data():
499 # Get a reference to the current event loop because
500 # we want to access low-level APIs.
501 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200502
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700503 # Create a pair of connected sockets.
504 rsock, wsock = socket.socketpair()
505
506 # Register the open socket to wait for data.
507 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200508
509 # Simulate the reception of data from the network
510 loop.call_soon(wsock.send, 'abc'.encode())
511
512 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200513 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200514
515 # Got data, we are done: close the socket
516 print("Received:", data.decode())
517 writer.close()
518
519 # Close the second socket
520 wsock.close()
521
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700522 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200523
524.. seealso::
525
526 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400527 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700528 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200529
530 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400531 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700532 :meth:`loop.add_reader` method to watch a file descriptor.