blob: e686a6a1c4cd3240813cea75ca70aefa0d95fbcc [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 Svetlov11194c82018-09-13 16:53:49 -070025 await writer.awrite(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 Svetlov11194c82018-09-13 16:53:49 -070031 await writer.aclose()
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 Svetlov11194c82018-09-13 16:53:49 -0700229 .. coroutinemethod:: awrite(data)
230
231 Write *data* to the stream.
232
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400233 The method respects flow control, execution is paused if the write
234 buffer reaches the high watermark.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700235
236 .. versionadded:: 3.8
237
238 .. coroutinemethod:: aclose()
239
240 Close the stream.
241
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400242 Wait until all closing actions are complete, e.g. SSL shutdown for
Andrew Svetlov11194c82018-09-13 16:53:49 -0700243 secure sockets.
244
245 .. versionadded:: 3.8
246
247 .. method:: can_write_eof()
248
249 Return *True* if the underlying transport supports
250 the :meth:`write_eof` method, *False* otherwise.
251
252 .. method:: write_eof()
253
254 Close the write end of the stream after the buffered write
255 data is flushed.
256
257 .. attribute:: transport
258
259 Return the underlying asyncio transport.
260
261 .. method:: get_extra_info(name, default=None)
262
263 Access optional transport information; see
264 :meth:`BaseTransport.get_extra_info` for details.
265
Yury Selivanov8be876e2018-09-11 17:10:37 -0700266 .. method:: write(data)
Victor Stinner83704962015-02-25 14:24:15 +0100267
Yury Selivanov8be876e2018-09-11 17:10:37 -0700268 Write *data* to the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100269
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400270 This method is not subject to flow control. Calls to ``write()`` should
271 be followed by :meth:`drain`. The :meth:`awrite` method is a
272 recommended alternative the applies flow control automatically.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700273
Yury Selivanov8be876e2018-09-11 17:10:37 -0700274 .. method:: writelines(data)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100275
Yury Selivanov8be876e2018-09-11 17:10:37 -0700276 Write a list (or any iterable) of bytes to the stream.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100277
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400278 This method is not subject to flow control. Calls to ``writelines()``
279 should be followed by :meth:`drain`.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700280
Yury Selivanov8be876e2018-09-11 17:10:37 -0700281 .. coroutinemethod:: drain()
282
283 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400284 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700285
286 writer.write(data)
287 await writer.drain()
288
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400289 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700290 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400291 the high watermark, *drain()* blocks until the size of the
292 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700293 be resumed. When there is nothing to wait for, the :meth:`drain`
294 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100295
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100296 .. method:: close()
297
Yury Selivanov8be876e2018-09-11 17:10:37 -0700298 Close the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100299
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200300 .. method:: is_closing()
301
Yury Selivanov8be876e2018-09-11 17:10:37 -0700302 Return ``True`` if the stream is closed or in the process of
303 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200304
305 .. versionadded:: 3.7
306
307 .. coroutinemethod:: wait_closed()
308
Yury Selivanov8be876e2018-09-11 17:10:37 -0700309 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200310
Yury Selivanov8be876e2018-09-11 17:10:37 -0700311 Should be called after :meth:`close` to wait until the underlying
312 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200313
314 .. versionadded:: 3.7
315
Victor Stinnerc520edc2014-01-23 11:25:48 +0100316
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700317Examples
318========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200319
Victor Stinnered051592014-10-12 20:18:16 +0200320.. _asyncio-tcp-echo-client-streams:
321
322TCP echo client using streams
323-----------------------------
324
325TCP echo client using the :func:`asyncio.open_connection` function::
326
327 import asyncio
328
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700329 async def tcp_echo_client(message):
330 reader, writer = await asyncio.open_connection(
331 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200332
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700333 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200334 writer.write(message.encode())
335
Andrew Svetlov88743422017-12-11 17:35:49 +0200336 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700337 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200338
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700339 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200340 writer.close()
341
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700342 asyncio.run(tcp_echo_client('Hello World!'))
343
Victor Stinnered051592014-10-12 20:18:16 +0200344
345.. seealso::
346
Yury Selivanov394374e2018-09-17 15:35:24 -0400347 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700348 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200349
350
351.. _asyncio-tcp-echo-server-streams:
352
353TCP echo server using streams
354-----------------------------
355
356TCP echo server using the :func:`asyncio.start_server` function::
357
358 import asyncio
359
Andrew Svetlov88743422017-12-11 17:35:49 +0200360 async def handle_echo(reader, writer):
361 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200362 message = data.decode()
363 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200364
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700365 print(f"Received {message!r} from {addr!r}")
366
367 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200368 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200369 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200370
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700371 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200372 writer.close()
373
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700374 async def main():
375 server = await asyncio.start_server(
376 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200377
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700378 addr = server.sockets[0].getsockname()
379 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200380
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700381 async with server:
382 await server.serve_forever()
383
384 asyncio.run(main())
385
Victor Stinnered051592014-10-12 20:18:16 +0200386
387.. seealso::
388
Yury Selivanov394374e2018-09-17 15:35:24 -0400389 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700390 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200391
392
Victor Stinner5121a9b2014-10-11 15:52:14 +0200393Get HTTP headers
394----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100395
396Simple example querying HTTP headers of the URL passed on the command line::
397
398 import asyncio
399 import urllib.parse
400 import sys
401
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400402 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100403 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200404 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700405 reader, writer = await asyncio.open_connection(
406 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200407 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700408 reader, writer = await asyncio.open_connection(
409 url.hostname, 80)
410
411 query = (
412 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
413 f"Host: {url.hostname}\r\n"
414 f"\r\n"
415 )
416
Victor Stinnerc520edc2014-01-23 11:25:48 +0100417 writer.write(query.encode('latin-1'))
418 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200419 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100420 if not line:
421 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700422
Victor Stinnerc520edc2014-01-23 11:25:48 +0100423 line = line.decode('latin1').rstrip()
424 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700425 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100426
Victor Stinner5121a9b2014-10-11 15:52:14 +0200427 # Ignore the body, close the socket
428 writer.close()
429
Victor Stinnerc520edc2014-01-23 11:25:48 +0100430 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700431 asyncio.run(print_http_headers(url))
432
Victor Stinnerc520edc2014-01-23 11:25:48 +0100433
434Usage::
435
436 python example.py http://example.com/path/page.html
437
Victor Stinner04e6df32014-10-11 16:16:27 +0200438or with HTTPS::
439
440 python example.py https://example.com/path/page.html
441
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700442
Yury Selivanov394374e2018-09-17 15:35:24 -0400443.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200444
445Register an open socket to wait for data using streams
446------------------------------------------------------
447
448Coroutine waiting until a socket receives data using the
449:func:`open_connection` function::
450
451 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700452 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200453
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700454 async def wait_for_data():
455 # Get a reference to the current event loop because
456 # we want to access low-level APIs.
457 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200458
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700459 # Create a pair of connected sockets.
460 rsock, wsock = socket.socketpair()
461
462 # Register the open socket to wait for data.
463 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200464
465 # Simulate the reception of data from the network
466 loop.call_soon(wsock.send, 'abc'.encode())
467
468 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200469 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200470
471 # Got data, we are done: close the socket
472 print("Received:", data.decode())
473 writer.close()
474
475 # Close the second socket
476 wsock.close()
477
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700478 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200479
480.. seealso::
481
482 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400483 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700484 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200485
486 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400487 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700488 :meth:`loop.add_reader` method to watch a file descriptor.