blob: 269c3dc80c471dbdce420a2918b6a2b6d93d623e [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
Miss Islington (bot)6eb34772022-02-18 01:30:36 -080069 .. versionchanged:: 3.7
70 Added the *ssl_handshake_timeout* parameter.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040071
Miss Islington (bot)6eb34772022-02-18 01:30:36 -080072 .. versionchanged:: 3.10
73 Removed the *loop* parameter.
Miss Islington (bot)150a8e82021-05-26 15:19:42 -070074
75
Yury Selivanov7c7605f2018-09-11 09:54:40 -070076.. coroutinefunction:: start_server(client_connected_cb, host=None, \
Andre Delfinodcc997c2020-12-16 22:37:28 -030077 port=None, *, limit=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078 family=socket.AF_UNSPEC, \
79 flags=socket.AI_PASSIVE, sock=None, \
80 backlog=100, ssl=None, reuse_address=None, \
81 reuse_port=None, ssl_handshake_timeout=None, \
82 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010083
Yury Selivanov7c7605f2018-09-11 09:54:40 -070084 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010085
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040086 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070087 connection is established. It receives a ``(reader, writer)`` pair
88 as two arguments, instances of the :class:`StreamReader` and
89 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010090
Yury Selivanov7c7605f2018-09-11 09:54:40 -070091 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040092 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040093 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010094
Yury Selivanov7c7605f2018-09-11 09:54:40 -070095 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070096 returned :class:`StreamReader` instance. By default the *limit*
97 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040098
99 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700100 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100101
Miss Islington (bot)6eb34772022-02-18 01:30:36 -0800102 .. versionchanged:: 3.7
103 Added the *ssl_handshake_timeout* and *start_serving* parameters.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400104
Miss Islington (bot)6eb34772022-02-18 01:30:36 -0800105 .. versionchanged:: 3.10
106 Removed the *loop* parameter.
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700107
Yury Selivanov8be876e2018-09-11 17:10:37 -0700108
109.. rubric:: Unix Sockets
110
Andre Delfinodcc997c2020-12-16 22:37:28 -0300111.. coroutinefunction:: open_unix_connection(path=None, *, limit=None, \
Yurii Karabas86150d32020-11-29 14:50:57 +0200112 ssl=None, sock=None, server_hostname=None, \
113 ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500114
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400115 Establish a Unix socket connection and return a pair of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700116 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500117
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400118 Similar to :func:`open_connection` but operates on Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400119
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700120 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500121
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400122 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500123
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400124 .. versionchanged:: 3.7
Miss Islington (bot)6eb34772022-02-18 01:30:36 -0800125 Added the *ssl_handshake_timeout* parameter.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400126 The *path* parameter can now be a :term:`path-like object`
127
Miss Islington (bot)6eb34772022-02-18 01:30:36 -0800128 .. versionchanged:: 3.10
129 Removed the *loop* parameter.
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700130
Yury Selivanov8be876e2018-09-11 17:10:37 -0700131
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700132.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
Andre Delfinodcc997c2020-12-16 22:37:28 -0300133 *, limit=None, sock=None, backlog=100, ssl=None, \
Yurii Karabas86150d32020-11-29 14:50:57 +0200134 ssl_handshake_timeout=None, start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500135
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400136 Start a Unix socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500137
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400138 Similar to :func:`start_server` but works with Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400139
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700140 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500141
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400142 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500143
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400144 .. versionchanged:: 3.7
Miss Islington (bot)6eb34772022-02-18 01:30:36 -0800145 Added the *ssl_handshake_timeout* and *start_serving* parameters.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400146 The *path* parameter can now be a :term:`path-like object`.
147
Miss Islington (bot)6eb34772022-02-18 01:30:36 -0800148 .. versionchanged:: 3.10
149 Removed the *loop* parameter.
Miss Islington (bot)150a8e82021-05-26 15:19:42 -0700150
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700151
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100152StreamReader
153============
154
Yury Selivanov8be876e2018-09-11 17:10:37 -0700155.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100156
Yury Selivanov8be876e2018-09-11 17:10:37 -0700157 Represents a reader object that provides APIs to read data
158 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100159
Yury Selivanov8be876e2018-09-11 17:10:37 -0700160 It is not recommended to instantiate *StreamReader* objects
161 directly; use :func:`open_connection` and :func:`start_server`
162 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100163
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100164 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500166 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
167 read until EOF and return all read bytes.
168
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400169 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500170 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100171
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100172 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100173
Yury Selivanov8be876e2018-09-11 17:10:37 -0700174 Read one line, where "line" is a sequence of bytes
175 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500176
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400177 If EOF is received and ``\n`` was not found, the method
Yury Selivanov8be876e2018-09-11 17:10:37 -0700178 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500179
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400180 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500181 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100182
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100183 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100184
Yury Selivanov8be876e2018-09-11 17:10:37 -0700185 Read exactly *n* bytes.
186
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400187 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
Yury Selivanov8be876e2018-09-11 17:10:37 -0700188 can be read. Use the :attr:`IncompleteReadError.partial`
189 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100190
Julien Palard5c1f15b2021-01-25 15:46:06 +0100191 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400192
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400193 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400194
195 On success, the data and separator will be removed from the
196 internal buffer (consumed). Returned data will include the
197 separator at the end.
198
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400199 If the amount of data read exceeds the configured stream limit, a
200 :exc:`LimitOverrunError` exception is raised, and the data
201 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400202
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400203 If EOF is reached before the complete separator is found,
204 an :exc:`IncompleteReadError` exception is raised, and the internal
205 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
206 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400207
208 .. versionadded:: 3.5.2
209
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500210 .. method:: at_eof()
211
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700212 Return ``True`` if the buffer is empty and :meth:`feed_eof`
213 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500214
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100215
216StreamWriter
217============
218
Yury Selivanov8be876e2018-09-11 17:10:37 -0700219.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100220
Yury Selivanov8be876e2018-09-11 17:10:37 -0700221 Represents a writer object that provides APIs to write data
222 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100223
Yury Selivanov8be876e2018-09-11 17:10:37 -0700224 It is not recommended to instantiate *StreamWriter* objects
225 directly; use :func:`open_connection` and :func:`start_server`
226 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100227
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400228 .. method:: write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700229
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400230 The method attempts to write the *data* to the underlying socket immediately.
231 If that fails, the data is queued in an internal write buffer until it can be
232 sent.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700233
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700234 The method should be used along with the ``drain()`` method::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700235
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400236 stream.write(data)
237 await stream.drain()
Andrew Svetlov11194c82018-09-13 16:53:49 -0700238
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400239 .. method:: writelines(data)
240
241 The method writes a list (or any iterable) of bytes to the underlying socket
242 immediately.
243 If that fails, the data is queued in an internal write buffer until it can be
244 sent.
245
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700246 The method should be used along with the ``drain()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400247
248 stream.writelines(lines)
249 await stream.drain()
250
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400251 .. method:: close()
252
253 The method closes the stream and the underlying socket.
254
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700255 The method should be used along with the ``wait_closed()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400256
257 stream.close()
258 await stream.wait_closed()
259
Andrew Svetlov11194c82018-09-13 16:53:49 -0700260 .. method:: can_write_eof()
261
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200262 Return ``True`` if the underlying transport supports
263 the :meth:`write_eof` method, ``False`` otherwise.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700264
265 .. method:: write_eof()
266
267 Close the write end of the stream after the buffered write
268 data is flushed.
269
270 .. attribute:: transport
271
272 Return the underlying asyncio transport.
273
274 .. method:: get_extra_info(name, default=None)
275
276 Access optional transport information; see
277 :meth:`BaseTransport.get_extra_info` for details.
278
Yury Selivanov8be876e2018-09-11 17:10:37 -0700279 .. coroutinemethod:: drain()
280
281 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400282 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700283
284 writer.write(data)
285 await writer.drain()
286
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400287 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700288 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400289 the high watermark, *drain()* blocks until the size of the
290 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700291 be resumed. When there is nothing to wait for, the :meth:`drain`
292 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100293
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200294 .. method:: is_closing()
295
Yury Selivanov8be876e2018-09-11 17:10:37 -0700296 Return ``True`` if the stream is closed or in the process of
297 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200298
299 .. versionadded:: 3.7
300
301 .. coroutinemethod:: wait_closed()
302
Yury Selivanov8be876e2018-09-11 17:10:37 -0700303 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200304
Yury Selivanov8be876e2018-09-11 17:10:37 -0700305 Should be called after :meth:`close` to wait until the underlying
306 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200307
308 .. versionadded:: 3.7
309
Victor Stinnerc520edc2014-01-23 11:25:48 +0100310
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700311Examples
312========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200313
Victor Stinnered051592014-10-12 20:18:16 +0200314.. _asyncio-tcp-echo-client-streams:
315
316TCP echo client using streams
317-----------------------------
318
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700319TCP echo client using the :func:`asyncio.open_connection` function::
Victor Stinnered051592014-10-12 20:18:16 +0200320
321 import asyncio
322
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700323 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700324 reader, writer = await asyncio.open_connection(
325 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200326
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700327 print(f'Send: {message!r}')
328 writer.write(message.encode())
329
330 data = await reader.read(100)
331 print(f'Received: {data.decode()!r}')
332
333 print('Close the connection')
334 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200335
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700336 asyncio.run(tcp_echo_client('Hello World!'))
337
Victor Stinnered051592014-10-12 20:18:16 +0200338
339.. seealso::
340
Yury Selivanov394374e2018-09-17 15:35:24 -0400341 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700342 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200343
344
345.. _asyncio-tcp-echo-server-streams:
346
347TCP echo server using streams
348-----------------------------
349
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700350TCP echo server using the :func:`asyncio.start_server` function::
Victor Stinnered051592014-10-12 20:18:16 +0200351
352 import asyncio
353
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700354 async def handle_echo(reader, writer):
355 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200356 message = data.decode()
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700357 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200358
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700359 print(f"Received {message!r} from {addr!r}")
360
361 print(f"Send: {message!r}")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700362 writer.write(data)
363 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200364
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700365 print("Close the connection")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700366 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200367
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368 async def main():
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700369 server = await asyncio.start_server(
370 handle_echo, '127.0.0.1', 8888)
371
Miss Islington (bot)bb4f8852021-10-11 12:34:47 -0700372 addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
373 print(f'Serving on {addrs}')
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700374
375 async with server:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700376 await server.serve_forever()
377
378 asyncio.run(main())
379
Victor Stinnered051592014-10-12 20:18:16 +0200380
381.. seealso::
382
Yury Selivanov394374e2018-09-17 15:35:24 -0400383 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700384 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200385
386
Victor Stinner5121a9b2014-10-11 15:52:14 +0200387Get HTTP headers
388----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100389
390Simple example querying HTTP headers of the URL passed on the command line::
391
392 import asyncio
393 import urllib.parse
394 import sys
395
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400396 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100397 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200398 if url.scheme == 'https':
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700399 reader, writer = await asyncio.open_connection(
400 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200401 else:
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700402 reader, writer = await asyncio.open_connection(
403 url.hostname, 80)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700404
405 query = (
406 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
407 f"Host: {url.hostname}\r\n"
408 f"\r\n"
409 )
410
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700411 writer.write(query.encode('latin-1'))
412 while True:
413 line = await reader.readline()
414 if not line:
415 break
416
Victor Stinnerc520edc2014-01-23 11:25:48 +0100417 line = line.decode('latin1').rstrip()
418 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700419 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100420
Victor Stinner5121a9b2014-10-11 15:52:14 +0200421 # Ignore the body, close the socket
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700422 writer.close()
Victor Stinner5121a9b2014-10-11 15:52:14 +0200423
Victor Stinnerc520edc2014-01-23 11:25:48 +0100424 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700425 asyncio.run(print_http_headers(url))
426
Victor Stinnerc520edc2014-01-23 11:25:48 +0100427
428Usage::
429
430 python example.py http://example.com/path/page.html
431
Victor Stinner04e6df32014-10-11 16:16:27 +0200432or with HTTPS::
433
434 python example.py https://example.com/path/page.html
435
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700436
Yury Selivanov394374e2018-09-17 15:35:24 -0400437.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200438
439Register an open socket to wait for data using streams
440------------------------------------------------------
441
442Coroutine waiting until a socket receives data using the
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700443:func:`open_connection` function::
Victor Stinner04e6df32014-10-11 16:16:27 +0200444
445 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700446 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200447
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700448 async def wait_for_data():
449 # Get a reference to the current event loop because
450 # we want to access low-level APIs.
451 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200452
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700453 # Create a pair of connected sockets.
454 rsock, wsock = socket.socketpair()
455
456 # Register the open socket to wait for data.
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700457 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200458
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700459 # Simulate the reception of data from the network
460 loop.call_soon(wsock.send, 'abc'.encode())
Victor Stinner04e6df32014-10-11 16:16:27 +0200461
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700462 # Wait for data
463 data = await reader.read(100)
464
465 # Got data, we are done: close the socket
466 print("Received:", data.decode())
467 writer.close()
Victor Stinner04e6df32014-10-11 16:16:27 +0200468
469 # Close the second socket
470 wsock.close()
471
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700472 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200473
474.. seealso::
475
476 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400477 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700478 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200479
480 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400481 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482 :meth:`loop.add_reader` method to watch a file descriptor.