blob: e735b81f234d2679148da041a1664860ffc6f829 [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
Yury Selivanov7c7605f2018-09-11 09:54:40 -070070.. coroutinefunction:: start_server(client_connected_cb, host=None, \
71 port=None, \*, loop=None, limit=None, \
72 family=socket.AF_UNSPEC, \
73 flags=socket.AI_PASSIVE, sock=None, \
74 backlog=100, ssl=None, reuse_address=None, \
75 reuse_port=None, ssl_handshake_timeout=None, \
76 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010077
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010079
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040080 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070081 connection is established. It receives a ``(reader, writer)`` pair
82 as two arguments, instances of the :class:`StreamReader` and
83 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010084
Yury Selivanov7c7605f2018-09-11 09:54:40 -070085 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040086 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040087 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010088
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089 The *loop* argument is optional and can always be determined
90 automatically when this method is awaited from a coroutine.
91
92 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070093 returned :class:`StreamReader` instance. By default the *limit*
94 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040095
96 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070097 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010098
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040099 .. versionadded:: 3.7
100
101 The *ssl_handshake_timeout* and *start_serving* parameters.
102
Yury Selivanov8be876e2018-09-11 17:10:37 -0700103
104.. rubric:: Unix Sockets
105
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700106.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
107 limit=None, ssl=None, sock=None, \
108 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500109
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400110 Establish a Unix socket connection and return a pair of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700111 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500112
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400113 Similar to :func:`open_connection` but operates on Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400114
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700115 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500116
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400117 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500118
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400119 .. versionadded:: 3.7
120
121 The *ssl_handshake_timeout* parameter.
122
123 .. versionchanged:: 3.7
124
125 The *path* parameter can now be a :term:`path-like object`
126
Yury Selivanov8be876e2018-09-11 17:10:37 -0700127
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700128.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
129 \*, loop=None, limit=None, sock=None, \
130 backlog=100, ssl=None, ssl_handshake_timeout=None, \
131 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500132
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400133 Start a Unix socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500134
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400135 Similar to :func:`start_server` but works with Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400136
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700137 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500138
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400139 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500140
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400141 .. versionadded:: 3.7
142
143 The *ssl_handshake_timeout* and *start_serving* parameters.
144
145 .. versionchanged:: 3.7
146
147 The *path* parameter can now be a :term:`path-like object`.
148
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100149
Yury Selivanov8be876e2018-09-11 17:10:37 -0700150---------
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700151
152
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100153StreamReader
154============
155
Yury Selivanov8be876e2018-09-11 17:10:37 -0700156.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100157
Yury Selivanov8be876e2018-09-11 17:10:37 -0700158 Represents a reader object that provides APIs to read data
159 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100160
Yury Selivanov8be876e2018-09-11 17:10:37 -0700161 It is not recommended to instantiate *StreamReader* objects
162 directly; use :func:`open_connection` and :func:`start_server`
163 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100164
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100165 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100166
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500167 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
168 read until EOF and return all read bytes.
169
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400170 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500171 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100172
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100173 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100174
Yury Selivanov8be876e2018-09-11 17:10:37 -0700175 Read one line, where "line" is a sequence of bytes
176 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500177
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400178 If EOF is received and ``\n`` was not found, the method
Yury Selivanov8be876e2018-09-11 17:10:37 -0700179 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500180
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400181 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500182 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100183
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100184 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100185
Yury Selivanov8be876e2018-09-11 17:10:37 -0700186 Read exactly *n* bytes.
187
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400188 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
Yury Selivanov8be876e2018-09-11 17:10:37 -0700189 can be read. Use the :attr:`IncompleteReadError.partial`
190 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100191
Berker Peksage5b0bd12016-10-18 00:34:46 +0300192 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400193
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400194 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400195
196 On success, the data and separator will be removed from the
197 internal buffer (consumed). Returned data will include the
198 separator at the end.
199
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400200 If the amount of data read exceeds the configured stream limit, a
201 :exc:`LimitOverrunError` exception is raised, and the data
202 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400203
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400204 If EOF is reached before the complete separator is found,
205 an :exc:`IncompleteReadError` exception is raised, and the internal
206 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
207 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400208
209 .. versionadded:: 3.5.2
210
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500211 .. method:: at_eof()
212
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700213 Return ``True`` if the buffer is empty and :meth:`feed_eof`
214 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500215
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100216
217StreamWriter
218============
219
Yury Selivanov8be876e2018-09-11 17:10:37 -0700220.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100221
Yury Selivanov8be876e2018-09-11 17:10:37 -0700222 Represents a writer object that provides APIs to write data
223 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100224
Yury Selivanov8be876e2018-09-11 17:10:37 -0700225 It is not recommended to instantiate *StreamWriter* objects
226 directly; use :func:`open_connection` and :func:`start_server`
227 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100228
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400229 .. method:: write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700230
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400231 The method attempts to write the *data* to the underlying socket immediately.
232 If that fails, the data is queued in an internal write buffer until it can be
233 sent.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700234
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400235 Starting with Python 3.8, it is possible to directly await on the `write()`
236 method::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700237
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400238 await stream.write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700239
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400240 The ``await`` pauses the current coroutine until the data is written to the
241 socket.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700242
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400243 Below is an equivalent code that works with Python <= 3.7::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700244
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400245 stream.write(data)
246 await stream.drain()
Andrew Svetlov11194c82018-09-13 16:53:49 -0700247
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400248 .. versionchanged:: 3.8
249 Support ``await stream.write(...)`` syntax.
250
251 .. method:: writelines(data)
252
253 The method writes a list (or any iterable) of bytes to the underlying socket
254 immediately.
255 If that fails, the data is queued in an internal write buffer until it can be
256 sent.
257
258 Starting with Python 3.8, it is possible to directly await on the `write()`
259 method::
260
261 await stream.writelines(lines)
262
263 The ``await`` pauses the current coroutine until the data is written to the
264 socket.
265
266 Below is an equivalent code that works with Python <= 3.7::
267
268 stream.writelines(lines)
269 await stream.drain()
270
271 .. versionchanged:: 3.8
272 Support ``await stream.writelines()`` syntax.
273
274 .. method:: close()
275
276 The method closes the stream and the underlying socket.
277
278 Starting with Python 3.8, it is possible to directly await on the `close()`
279 method::
280
281 await stream.close()
282
283 The ``await`` pauses the current coroutine until the stream and the underlying
284 socket are closed (and SSL shutdown is performed for a secure connection).
285
286 Below is an equivalent code that works with Python <= 3.7::
287
288 stream.close()
289 await stream.wait_closed()
290
291 .. versionchanged:: 3.8
292 Support ``await stream.close()`` syntax.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700293
294 .. method:: can_write_eof()
295
296 Return *True* if the underlying transport supports
297 the :meth:`write_eof` method, *False* otherwise.
298
299 .. method:: write_eof()
300
301 Close the write end of the stream after the buffered write
302 data is flushed.
303
304 .. attribute:: transport
305
306 Return the underlying asyncio transport.
307
308 .. method:: get_extra_info(name, default=None)
309
310 Access optional transport information; see
311 :meth:`BaseTransport.get_extra_info` for details.
312
Yury Selivanov8be876e2018-09-11 17:10:37 -0700313 .. coroutinemethod:: drain()
314
315 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400316 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700317
318 writer.write(data)
319 await writer.drain()
320
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400321 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700322 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400323 the high watermark, *drain()* blocks until the size of the
324 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700325 be resumed. When there is nothing to wait for, the :meth:`drain`
326 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100327
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200328 .. method:: is_closing()
329
Yury Selivanov8be876e2018-09-11 17:10:37 -0700330 Return ``True`` if the stream is closed or in the process of
331 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200332
333 .. versionadded:: 3.7
334
335 .. coroutinemethod:: wait_closed()
336
Yury Selivanov8be876e2018-09-11 17:10:37 -0700337 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200338
Yury Selivanov8be876e2018-09-11 17:10:37 -0700339 Should be called after :meth:`close` to wait until the underlying
340 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200341
342 .. versionadded:: 3.7
343
Victor Stinnerc520edc2014-01-23 11:25:48 +0100344
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700345Examples
346========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200347
Victor Stinnered051592014-10-12 20:18:16 +0200348.. _asyncio-tcp-echo-client-streams:
349
350TCP echo client using streams
351-----------------------------
352
353TCP echo client using the :func:`asyncio.open_connection` function::
354
355 import asyncio
356
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700357 async def tcp_echo_client(message):
358 reader, writer = await asyncio.open_connection(
359 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200360
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700361 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200362 writer.write(message.encode())
363
Andrew Svetlov88743422017-12-11 17:35:49 +0200364 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700365 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200366
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700367 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200368 writer.close()
369
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700370 asyncio.run(tcp_echo_client('Hello World!'))
371
Victor Stinnered051592014-10-12 20:18:16 +0200372
373.. seealso::
374
Yury Selivanov394374e2018-09-17 15:35:24 -0400375 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700376 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200377
378
379.. _asyncio-tcp-echo-server-streams:
380
381TCP echo server using streams
382-----------------------------
383
384TCP echo server using the :func:`asyncio.start_server` function::
385
386 import asyncio
387
Andrew Svetlov88743422017-12-11 17:35:49 +0200388 async def handle_echo(reader, writer):
389 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200390 message = data.decode()
391 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200392
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700393 print(f"Received {message!r} from {addr!r}")
394
395 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200396 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200397 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200398
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700399 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200400 writer.close()
401
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700402 async def main():
403 server = await asyncio.start_server(
404 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200405
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700406 addr = server.sockets[0].getsockname()
407 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200408
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700409 async with server:
410 await server.serve_forever()
411
412 asyncio.run(main())
413
Victor Stinnered051592014-10-12 20:18:16 +0200414
415.. seealso::
416
Yury Selivanov394374e2018-09-17 15:35:24 -0400417 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700418 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200419
420
Victor Stinner5121a9b2014-10-11 15:52:14 +0200421Get HTTP headers
422----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100423
424Simple example querying HTTP headers of the URL passed on the command line::
425
426 import asyncio
427 import urllib.parse
428 import sys
429
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400430 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100431 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200432 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700433 reader, writer = await asyncio.open_connection(
434 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200435 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700436 reader, writer = await asyncio.open_connection(
437 url.hostname, 80)
438
439 query = (
440 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
441 f"Host: {url.hostname}\r\n"
442 f"\r\n"
443 )
444
Victor Stinnerc520edc2014-01-23 11:25:48 +0100445 writer.write(query.encode('latin-1'))
446 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200447 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100448 if not line:
449 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700450
Victor Stinnerc520edc2014-01-23 11:25:48 +0100451 line = line.decode('latin1').rstrip()
452 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700453 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100454
Victor Stinner5121a9b2014-10-11 15:52:14 +0200455 # Ignore the body, close the socket
456 writer.close()
457
Victor Stinnerc520edc2014-01-23 11:25:48 +0100458 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700459 asyncio.run(print_http_headers(url))
460
Victor Stinnerc520edc2014-01-23 11:25:48 +0100461
462Usage::
463
464 python example.py http://example.com/path/page.html
465
Victor Stinner04e6df32014-10-11 16:16:27 +0200466or with HTTPS::
467
468 python example.py https://example.com/path/page.html
469
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700470
Yury Selivanov394374e2018-09-17 15:35:24 -0400471.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200472
473Register an open socket to wait for data using streams
474------------------------------------------------------
475
476Coroutine waiting until a socket receives data using the
477:func:`open_connection` function::
478
479 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700480 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200481
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482 async def wait_for_data():
483 # Get a reference to the current event loop because
484 # we want to access low-level APIs.
485 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200486
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700487 # Create a pair of connected sockets.
488 rsock, wsock = socket.socketpair()
489
490 # Register the open socket to wait for data.
491 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200492
493 # Simulate the reception of data from the network
494 loop.call_soon(wsock.send, 'abc'.encode())
495
496 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200497 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200498
499 # Got data, we are done: close the socket
500 print("Received:", data.decode())
501 writer.close()
502
503 # Close the second socket
504 wsock.close()
505
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700506 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200507
508.. seealso::
509
510 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400511 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700512 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200513
514 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400515 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700516 :meth:`loop.add_reader` method to watch a file descriptor.