blob: 95a8e4649beede07dca948eada56cd6099e2caea [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
Kyle Stanleyf9000642019-10-10 19:18:46 -04009**Source code:** :source:`Lib/asyncio/streams.py`
10
11-------------------------------------------------
12
Yury Selivanov7c7605f2018-09-11 09:54:40 -070013Streams are high-level async/await-ready primitives to work with
Yury Selivanov8be876e2018-09-11 17:10:37 -070014network connections. Streams allow sending and receiving data without
Yury Selivanov7c7605f2018-09-11 09:54:40 -070015using callbacks or low-level protocols and transports.
lf627d2c82017-07-25 17:03:51 -060016
Yury Selivanov7372c3b2018-09-14 15:11:24 -070017.. _asyncio_example_stream:
18
Yury Selivanov8be876e2018-09-11 17:10:37 -070019Here is an example of a TCP echo client written using asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -070020streams::
Victor Stinner24f8ebf2014-01-23 11:05:01 +010021
Yury Selivanov7c7605f2018-09-11 09:54:40 -070022 import asyncio
Guido van Rossum19ff6972015-10-19 13:18:04 -070023
Yury Selivanov7c7605f2018-09-11 09:54:40 -070024 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -070025 reader, writer = await asyncio.open_connection(
26 '127.0.0.1', 8888)
Yury Selivanov7c7605f2018-09-11 09:54:40 -070027
Yury Selivanov6758e6e2019-09-29 21:59:55 -070028 print(f'Send: {message!r}')
29 writer.write(message.encode())
30 await writer.drain()
31
32 data = await reader.read(100)
33 print(f'Received: {data.decode()!r}')
34
35 print('Close the connection')
36 writer.close()
37 await writer.wait_closed()
Yury Selivanov7c7605f2018-09-11 09:54:40 -070038
39 asyncio.run(tcp_echo_client('Hello World!'))
Guido van Rossum19ff6972015-10-19 13:18:04 -070040
41
Yury Selivanov8be876e2018-09-11 17:10:37 -070042See also the `Examples`_ section below.
43
44
Yury Selivanov7c7605f2018-09-11 09:54:40 -070045.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010046
Yury Selivanov7c7605f2018-09-11 09:54:40 -070047The following top-level asyncio functions can be used to create
48and work with streams:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010049
Victor Stinner24f8ebf2014-01-23 11:05:01 +010050
Andre Delfinodcc997c2020-12-16 22:37:28 -030051.. coroutinefunction:: open_connection(host=None, port=None, *, \
Yurii Karabas86150d32020-11-29 14:50:57 +020052 limit=None, ssl=None, family=0, proto=0, \
53 flags=0, sock=None, local_addr=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070054 server_hostname=None, ssl_handshake_timeout=None)
55
56 Establish a network connection and return a pair of
Yury Selivanov8be876e2018-09-11 17:10:37 -070057 ``(reader, writer)`` objects.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070058
59 The returned *reader* and *writer* objects are instances of
60 :class:`StreamReader` and :class:`StreamWriter` classes.
61
Yury Selivanov7c7605f2018-09-11 09:54:40 -070062 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070063 returned :class:`StreamReader` instance. By default the *limit*
64 is set to 64 KiB.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010065
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040066 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070067 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010068
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040069 .. versionadded:: 3.7
70
71 The *ssl_handshake_timeout* parameter.
72
Miss Islington (bot)150a8e82021-05-26 15:19:42 -070073 .. deprecated-removed:: 3.8 3.10
74
75 The ``loop`` parameter. This function has been implicitly getting the
76 current running loop since 3.7. See
77 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
78 for more information.
79
80
Yury Selivanov7c7605f2018-09-11 09:54:40 -070081.. coroutinefunction:: start_server(client_connected_cb, host=None, \
Andre Delfinodcc997c2020-12-16 22:37:28 -030082 port=None, *, limit=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070083 family=socket.AF_UNSPEC, \
84 flags=socket.AI_PASSIVE, sock=None, \
85 backlog=100, ssl=None, reuse_address=None, \
86 reuse_port=None, ssl_handshake_timeout=None, \
87 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010088
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010090
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040091 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070092 connection is established. It receives a ``(reader, writer)`` pair
93 as two arguments, instances of the :class:`StreamReader` and
94 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010095
Yury Selivanov7c7605f2018-09-11 09:54:40 -070096 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040097 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040098 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010099
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700100 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -0700101 returned :class:`StreamReader` instance. By default the *limit*
102 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400103
104 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700105 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100106
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400107 .. versionadded:: 3.7
108
109 The *ssl_handshake_timeout* and *start_serving* parameters.
110
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700111 .. deprecated-removed:: 3.8 3.10
112
113 The ``loop`` parameter. This function has been implicitly getting the
114 current running loop since 3.7. See
115 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
116 for more information.
117
Yury Selivanov8be876e2018-09-11 17:10:37 -0700118
119.. rubric:: Unix Sockets
120
Andre Delfinodcc997c2020-12-16 22:37:28 -0300121.. coroutinefunction:: open_unix_connection(path=None, *, limit=None, \
Yurii Karabas86150d32020-11-29 14:50:57 +0200122 ssl=None, sock=None, server_hostname=None, \
123 ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500124
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400125 Establish a Unix socket connection and return a pair of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700126 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500127
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400128 Similar to :func:`open_connection` but operates on Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400129
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700130 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500131
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400132 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500133
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400134 .. versionadded:: 3.7
135
136 The *ssl_handshake_timeout* parameter.
137
138 .. versionchanged:: 3.7
139
140 The *path* parameter can now be a :term:`path-like object`
141
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700142 .. deprecated-removed:: 3.8 3.10
143
144 The ``loop`` parameter. This function has been implicitly getting the
145 current running loop since 3.7. See
146 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
147 for more information.
148
Yury Selivanov8be876e2018-09-11 17:10:37 -0700149
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700150.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
Andre Delfinodcc997c2020-12-16 22:37:28 -0300151 *, limit=None, sock=None, backlog=100, ssl=None, \
Yurii Karabas86150d32020-11-29 14:50:57 +0200152 ssl_handshake_timeout=None, start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500153
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400154 Start a Unix socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500155
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400156 Similar to :func:`start_server` but works with Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400157
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700158 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500159
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400160 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500161
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400162 .. versionadded:: 3.7
163
164 The *ssl_handshake_timeout* and *start_serving* parameters.
165
166 .. versionchanged:: 3.7
167
168 The *path* parameter can now be a :term:`path-like object`.
169
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700170 .. deprecated-removed:: 3.8 3.10
171
172 The ``loop`` parameter. This function has been implicitly getting the
173 current running loop since 3.7. See
174 :ref:`What's New in 3.10's Removed section <whatsnew310-removed>`
175 for more information.
176
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700177
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100178StreamReader
179============
180
Yury Selivanov8be876e2018-09-11 17:10:37 -0700181.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100182
Yury Selivanov8be876e2018-09-11 17:10:37 -0700183 Represents a reader object that provides APIs to read data
184 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100185
Yury Selivanov8be876e2018-09-11 17:10:37 -0700186 It is not recommended to instantiate *StreamReader* objects
187 directly; use :func:`open_connection` and :func:`start_server`
188 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100189
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100190 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100191
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500192 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
193 read until EOF and return all read bytes.
194
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400195 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500196 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100197
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100198 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100199
Yury Selivanov8be876e2018-09-11 17:10:37 -0700200 Read one line, where "line" is a sequence of bytes
201 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500202
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400203 If EOF is received and ``\n`` was not found, the method
Yury Selivanov8be876e2018-09-11 17:10:37 -0700204 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500205
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400206 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500207 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100208
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100209 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100210
Yury Selivanov8be876e2018-09-11 17:10:37 -0700211 Read exactly *n* bytes.
212
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400213 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
Yury Selivanov8be876e2018-09-11 17:10:37 -0700214 can be read. Use the :attr:`IncompleteReadError.partial`
215 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100216
Julien Palard5c1f15b2021-01-25 15:46:06 +0100217 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400218
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400219 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400220
221 On success, the data and separator will be removed from the
222 internal buffer (consumed). Returned data will include the
223 separator at the end.
224
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400225 If the amount of data read exceeds the configured stream limit, a
226 :exc:`LimitOverrunError` exception is raised, and the data
227 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400228
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400229 If EOF is reached before the complete separator is found,
230 an :exc:`IncompleteReadError` exception is raised, and the internal
231 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
232 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400233
234 .. versionadded:: 3.5.2
235
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500236 .. method:: at_eof()
237
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700238 Return ``True`` if the buffer is empty and :meth:`feed_eof`
239 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500240
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100241
242StreamWriter
243============
244
Yury Selivanov8be876e2018-09-11 17:10:37 -0700245.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100246
Yury Selivanov8be876e2018-09-11 17:10:37 -0700247 Represents a writer object that provides APIs to write data
248 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100249
Yury Selivanov8be876e2018-09-11 17:10:37 -0700250 It is not recommended to instantiate *StreamWriter* objects
251 directly; use :func:`open_connection` and :func:`start_server`
252 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100253
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400254 .. method:: write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700255
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400256 The method attempts to write the *data* to the underlying socket immediately.
257 If that fails, the data is queued in an internal write buffer until it can be
258 sent.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700259
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700260 The method should be used along with the ``drain()`` method::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700261
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400262 stream.write(data)
263 await stream.drain()
Andrew Svetlov11194c82018-09-13 16:53:49 -0700264
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400265 .. method:: writelines(data)
266
267 The method writes a list (or any iterable) of bytes to the underlying socket
268 immediately.
269 If that fails, the data is queued in an internal write buffer until it can be
270 sent.
271
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700272 The method should be used along with the ``drain()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400273
274 stream.writelines(lines)
275 await stream.drain()
276
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400277 .. method:: close()
278
279 The method closes the stream and the underlying socket.
280
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700281 The method should be used along with the ``wait_closed()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400282
283 stream.close()
284 await stream.wait_closed()
285
Andrew Svetlov11194c82018-09-13 16:53:49 -0700286 .. method:: can_write_eof()
287
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200288 Return ``True`` if the underlying transport supports
289 the :meth:`write_eof` method, ``False`` otherwise.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700290
291 .. method:: write_eof()
292
293 Close the write end of the stream after the buffered write
294 data is flushed.
295
296 .. attribute:: transport
297
298 Return the underlying asyncio transport.
299
300 .. method:: get_extra_info(name, default=None)
301
302 Access optional transport information; see
303 :meth:`BaseTransport.get_extra_info` for details.
304
Yury Selivanov8be876e2018-09-11 17:10:37 -0700305 .. coroutinemethod:: drain()
306
307 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400308 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700309
310 writer.write(data)
311 await writer.drain()
312
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400313 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700314 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400315 the high watermark, *drain()* blocks until the size of the
316 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700317 be resumed. When there is nothing to wait for, the :meth:`drain`
318 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100319
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200320 .. method:: is_closing()
321
Yury Selivanov8be876e2018-09-11 17:10:37 -0700322 Return ``True`` if the stream is closed or in the process of
323 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200324
325 .. versionadded:: 3.7
326
327 .. coroutinemethod:: wait_closed()
328
Yury Selivanov8be876e2018-09-11 17:10:37 -0700329 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200330
Yury Selivanov8be876e2018-09-11 17:10:37 -0700331 Should be called after :meth:`close` to wait until the underlying
332 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200333
334 .. versionadded:: 3.7
335
Victor Stinnerc520edc2014-01-23 11:25:48 +0100336
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700337Examples
338========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200339
Victor Stinnered051592014-10-12 20:18:16 +0200340.. _asyncio-tcp-echo-client-streams:
341
342TCP echo client using streams
343-----------------------------
344
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700345TCP echo client using the :func:`asyncio.open_connection` function::
Victor Stinnered051592014-10-12 20:18:16 +0200346
347 import asyncio
348
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700349 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700350 reader, writer = await asyncio.open_connection(
351 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200352
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700353 print(f'Send: {message!r}')
354 writer.write(message.encode())
355
356 data = await reader.read(100)
357 print(f'Received: {data.decode()!r}')
358
359 print('Close the connection')
360 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200361
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700362 asyncio.run(tcp_echo_client('Hello World!'))
363
Victor Stinnered051592014-10-12 20:18:16 +0200364
365.. seealso::
366
Yury Selivanov394374e2018-09-17 15:35:24 -0400367 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200369
370
371.. _asyncio-tcp-echo-server-streams:
372
373TCP echo server using streams
374-----------------------------
375
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700376TCP echo server using the :func:`asyncio.start_server` function::
Victor Stinnered051592014-10-12 20:18:16 +0200377
378 import asyncio
379
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700380 async def handle_echo(reader, writer):
381 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200382 message = data.decode()
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700383 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200384
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700385 print(f"Received {message!r} from {addr!r}")
386
387 print(f"Send: {message!r}")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700388 writer.write(data)
389 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200390
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700391 print("Close the connection")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700392 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200393
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700394 async def main():
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700395 server = await asyncio.start_server(
396 handle_echo, '127.0.0.1', 8888)
397
Miss Islington (bot)bb4f8852021-10-11 12:34:47 -0700398 addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
399 print(f'Serving on {addrs}')
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700400
401 async with server:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700402 await server.serve_forever()
403
404 asyncio.run(main())
405
Victor Stinnered051592014-10-12 20:18:16 +0200406
407.. seealso::
408
Yury Selivanov394374e2018-09-17 15:35:24 -0400409 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700410 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200411
412
Victor Stinner5121a9b2014-10-11 15:52:14 +0200413Get HTTP headers
414----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100415
416Simple example querying HTTP headers of the URL passed on the command line::
417
418 import asyncio
419 import urllib.parse
420 import sys
421
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400422 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100423 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200424 if url.scheme == 'https':
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700425 reader, writer = await asyncio.open_connection(
426 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200427 else:
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700428 reader, writer = await asyncio.open_connection(
429 url.hostname, 80)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700430
431 query = (
432 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
433 f"Host: {url.hostname}\r\n"
434 f"\r\n"
435 )
436
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700437 writer.write(query.encode('latin-1'))
438 while True:
439 line = await reader.readline()
440 if not line:
441 break
442
Victor Stinnerc520edc2014-01-23 11:25:48 +0100443 line = line.decode('latin1').rstrip()
444 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700445 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100446
Victor Stinner5121a9b2014-10-11 15:52:14 +0200447 # Ignore the body, close the socket
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700448 writer.close()
Victor Stinner5121a9b2014-10-11 15:52:14 +0200449
Victor Stinnerc520edc2014-01-23 11:25:48 +0100450 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700451 asyncio.run(print_http_headers(url))
452
Victor Stinnerc520edc2014-01-23 11:25:48 +0100453
454Usage::
455
456 python example.py http://example.com/path/page.html
457
Victor Stinner04e6df32014-10-11 16:16:27 +0200458or with HTTPS::
459
460 python example.py https://example.com/path/page.html
461
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700462
Yury Selivanov394374e2018-09-17 15:35:24 -0400463.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200464
465Register an open socket to wait for data using streams
466------------------------------------------------------
467
468Coroutine waiting until a socket receives data using the
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700469:func:`open_connection` function::
Victor Stinner04e6df32014-10-11 16:16:27 +0200470
471 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700472 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200473
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700474 async def wait_for_data():
475 # Get a reference to the current event loop because
476 # we want to access low-level APIs.
477 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200478
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700479 # Create a pair of connected sockets.
480 rsock, wsock = socket.socketpair()
481
482 # Register the open socket to wait for data.
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700483 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200484
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700485 # Simulate the reception of data from the network
486 loop.call_soon(wsock.send, 'abc'.encode())
Victor Stinner04e6df32014-10-11 16:16:27 +0200487
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700488 # Wait for data
489 data = await reader.read(100)
490
491 # Got data, we are done: close the socket
492 print("Received:", data.decode())
493 writer.close()
Victor Stinner04e6df32014-10-11 16:16:27 +0200494
495 # Close the second socket
496 wsock.close()
497
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700498 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200499
500.. seealso::
501
502 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400503 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700504 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200505
506 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400507 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700508 :meth:`loop.add_reader` method to watch a file descriptor.