blob: 0489201b4d02fcd639c3bc2688503ab7429a7bc9 [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
57 automatically when this method is awaited from a coroutine.
58
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,
Yury Selivanov7c7605f2018-09-11 09:54:40 -070087 it will be automatically wrapped into 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
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700110 Establish a UNIX socket connection and return a pair of
111 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500112
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700113 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
117 Availability: UNIX.
118
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
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700133 Start a UNIX socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500134
Yury Selivanov8be876e2018-09-11 17:10:37 -0700135 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
139 Availability: UNIX.
140
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
Yury Selivanov8be876e2018-09-11 17:10:37 -0700170 If an 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
Yury Selivanov8be876e2018-09-11 17:10:37 -0700178 If an EOF is received and ``\n`` was not found, the method
179 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500180
Yury Selivanov8be876e2018-09-11 17:10:37 -0700181 If an 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
188 Raise an :exc:`IncompleteReadError` if an EOF reached before *n*
189 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
194 Read data from the stream until ``separator`` is found.
195
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
200 Configured stream limit is used to check result. Limit sets the
201 maximal length of data that can be returned, not counting the
202 separator.
203
204 If an EOF occurs and the complete separator is still not found,
205 an :exc:`IncompleteReadError` exception will be
206 raised, and the internal buffer will be reset. The
207 :attr:`IncompleteReadError.partial` attribute may contain the
208 separator partially.
209
210 If the data cannot be read because of over limit, a
211 :exc:`LimitOverrunError` exception will be raised, and the data
212 will be left in the internal buffer, so it can be read again.
213
214 .. versionadded:: 3.5.2
215
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500216 .. method:: at_eof()
217
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700218 Return ``True`` if the buffer is empty and :meth:`feed_eof`
219 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500220
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100221
222StreamWriter
223============
224
Yury Selivanov8be876e2018-09-11 17:10:37 -0700225.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100226
Yury Selivanov8be876e2018-09-11 17:10:37 -0700227 Represents a writer object that provides APIs to write data
228 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100229
Yury Selivanov8be876e2018-09-11 17:10:37 -0700230 It is not recommended to instantiate *StreamWriter* objects
231 directly; use :func:`open_connection` and :func:`start_server`
232 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100233
Andrew Svetlov11194c82018-09-13 16:53:49 -0700234 .. coroutinemethod:: awrite(data)
235
236 Write *data* to the stream.
237
238 The method respects control-flow, execution is paused if write
239 buffer reaches high-water limit.
240
241 .. versionadded:: 3.8
242
243 .. coroutinemethod:: aclose()
244
245 Close the stream.
246
247 Wait for finishing all closing actions, e.g. SSL shutdown for
248 secure sockets.
249
250 .. versionadded:: 3.8
251
252 .. method:: can_write_eof()
253
254 Return *True* if the underlying transport supports
255 the :meth:`write_eof` method, *False* otherwise.
256
257 .. method:: write_eof()
258
259 Close the write end of the stream after the buffered write
260 data is flushed.
261
262 .. attribute:: transport
263
264 Return the underlying asyncio transport.
265
266 .. method:: get_extra_info(name, default=None)
267
268 Access optional transport information; see
269 :meth:`BaseTransport.get_extra_info` for details.
270
Yury Selivanov8be876e2018-09-11 17:10:37 -0700271 .. method:: write(data)
Victor Stinner83704962015-02-25 14:24:15 +0100272
Yury Selivanov8be876e2018-09-11 17:10:37 -0700273 Write *data* to the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100274
Andrew Svetlov11194c82018-09-13 16:53:49 -0700275 This method doesn't apply control-flow. The call should be
276 followed by :meth:`drain`.
277
Yury Selivanov8be876e2018-09-11 17:10:37 -0700278 .. method:: writelines(data)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100279
Yury Selivanov8be876e2018-09-11 17:10:37 -0700280 Write a list (or any iterable) of bytes to the stream.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100281
Andrew Svetlov11194c82018-09-13 16:53:49 -0700282 This method doesn't apply control-flow. The call should be
283 followed by :meth:`drain`.
284
Yury Selivanov8be876e2018-09-11 17:10:37 -0700285 .. coroutinemethod:: drain()
286
287 Wait until it is appropriate to resume writing to the stream.
288 E.g.::
289
290 writer.write(data)
291 await writer.drain()
292
293 This is a flow-control method that interacts with the underlying
294 IO write buffer. When the size of the buffer reaches
295 the high-water limit, *drain()* blocks until the size of the
296 buffer is drained down to the low-water limit and writing can
297 be resumed. When there is nothing to wait for, the :meth:`drain`
298 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100299
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100300 .. method:: close()
301
Yury Selivanov8be876e2018-09-11 17:10:37 -0700302 Close the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100303
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200304 .. method:: is_closing()
305
Yury Selivanov8be876e2018-09-11 17:10:37 -0700306 Return ``True`` if the stream is closed or in the process of
307 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200308
309 .. versionadded:: 3.7
310
311 .. coroutinemethod:: wait_closed()
312
Yury Selivanov8be876e2018-09-11 17:10:37 -0700313 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200314
Yury Selivanov8be876e2018-09-11 17:10:37 -0700315 Should be called after :meth:`close` to wait until the underlying
316 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200317
318 .. versionadded:: 3.7
319
Victor Stinnerc520edc2014-01-23 11:25:48 +0100320
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700321Examples
322========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200323
Victor Stinnered051592014-10-12 20:18:16 +0200324.. _asyncio-tcp-echo-client-streams:
325
326TCP echo client using streams
327-----------------------------
328
329TCP echo client using the :func:`asyncio.open_connection` function::
330
331 import asyncio
332
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700333 async def tcp_echo_client(message):
334 reader, writer = await asyncio.open_connection(
335 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200336
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700337 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200338 writer.write(message.encode())
339
Andrew Svetlov88743422017-12-11 17:35:49 +0200340 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700341 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200342
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700343 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200344 writer.close()
345
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700346 asyncio.run(tcp_echo_client('Hello World!'))
347
Victor Stinnered051592014-10-12 20:18:16 +0200348
349.. seealso::
350
Yury Selivanov394374e2018-09-17 15:35:24 -0400351 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700352 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200353
354
355.. _asyncio-tcp-echo-server-streams:
356
357TCP echo server using streams
358-----------------------------
359
360TCP echo server using the :func:`asyncio.start_server` function::
361
362 import asyncio
363
Andrew Svetlov88743422017-12-11 17:35:49 +0200364 async def handle_echo(reader, writer):
365 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200366 message = data.decode()
367 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200368
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700369 print(f"Received {message!r} from {addr!r}")
370
371 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200372 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200373 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200374
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700375 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200376 writer.close()
377
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700378 async def main():
379 server = await asyncio.start_server(
380 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200381
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700382 addr = server.sockets[0].getsockname()
383 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200384
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700385 async with server:
386 await server.serve_forever()
387
388 asyncio.run(main())
389
Victor Stinnered051592014-10-12 20:18:16 +0200390
391.. seealso::
392
Yury Selivanov394374e2018-09-17 15:35:24 -0400393 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700394 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200395
396
Victor Stinner5121a9b2014-10-11 15:52:14 +0200397Get HTTP headers
398----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100399
400Simple example querying HTTP headers of the URL passed on the command line::
401
402 import asyncio
403 import urllib.parse
404 import sys
405
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400406 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100407 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200408 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700409 reader, writer = await asyncio.open_connection(
410 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200411 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700412 reader, writer = await asyncio.open_connection(
413 url.hostname, 80)
414
415 query = (
416 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
417 f"Host: {url.hostname}\r\n"
418 f"\r\n"
419 )
420
Victor Stinnerc520edc2014-01-23 11:25:48 +0100421 writer.write(query.encode('latin-1'))
422 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200423 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100424 if not line:
425 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700426
Victor Stinnerc520edc2014-01-23 11:25:48 +0100427 line = line.decode('latin1').rstrip()
428 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700429 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100430
Victor Stinner5121a9b2014-10-11 15:52:14 +0200431 # Ignore the body, close the socket
432 writer.close()
433
Victor Stinnerc520edc2014-01-23 11:25:48 +0100434 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700435 asyncio.run(print_http_headers(url))
436
Victor Stinnerc520edc2014-01-23 11:25:48 +0100437
438Usage::
439
440 python example.py http://example.com/path/page.html
441
Victor Stinner04e6df32014-10-11 16:16:27 +0200442or with HTTPS::
443
444 python example.py https://example.com/path/page.html
445
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700446
Yury Selivanov394374e2018-09-17 15:35:24 -0400447.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200448
449Register an open socket to wait for data using streams
450------------------------------------------------------
451
452Coroutine waiting until a socket receives data using the
453:func:`open_connection` function::
454
455 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700456 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200457
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700458 async def wait_for_data():
459 # Get a reference to the current event loop because
460 # we want to access low-level APIs.
461 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200462
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700463 # Create a pair of connected sockets.
464 rsock, wsock = socket.socketpair()
465
466 # Register the open socket to wait for data.
467 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200468
469 # Simulate the reception of data from the network
470 loop.call_soon(wsock.send, 'abc'.encode())
471
472 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200473 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200474
475 # Got data, we are done: close the socket
476 print("Received:", data.decode())
477 writer.close()
478
479 # Close the second socket
480 wsock.close()
481
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200483
484.. seealso::
485
486 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400487 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700488 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200489
490 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400491 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700492 :meth:`loop.add_reader` method to watch a file descriptor.