blob: 0cfecda91e99884dd93c64dfe2489265f012d9a2 [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 Selivanov8be876e2018-09-11 17:10:37 -070013Here is an example of a TCP echo client written using asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -070014streams::
Victor Stinner24f8ebf2014-01-23 11:05:01 +010015
Yury Selivanov7c7605f2018-09-11 09:54:40 -070016 import asyncio
Guido van Rossum19ff6972015-10-19 13:18:04 -070017
Yury Selivanov7c7605f2018-09-11 09:54:40 -070018 async def tcp_echo_client(message):
19 reader, writer = await asyncio.open_connection(
20 '127.0.0.1', 8888)
21
22 print(f'Send: {message!r}')
23 writer.write(message.encode())
24
25 data = await reader.read(100)
26 print(f'Received: {data.decode()!r}')
27
28 print('Close the connection')
29 writer.close()
30
31 asyncio.run(tcp_echo_client('Hello World!'))
Guido van Rossum19ff6972015-10-19 13:18:04 -070032
33
Yury Selivanov8be876e2018-09-11 17:10:37 -070034See also the `Examples`_ section below.
35
36
Yury Selivanov7c7605f2018-09-11 09:54:40 -070037.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010038
Yury Selivanov7c7605f2018-09-11 09:54:40 -070039The following top-level asyncio functions can be used to create
40and work with streams:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010041
Victor Stinner24f8ebf2014-01-23 11:05:01 +010042
Yury Selivanov7c7605f2018-09-11 09:54:40 -070043.. coroutinefunction:: open_connection(host=None, port=None, \*, \
44 loop=None, limit=None, ssl=None, family=0, \
45 proto=0, flags=0, sock=None, local_addr=None, \
46 server_hostname=None, ssl_handshake_timeout=None)
47
48 Establish a network connection and return a pair of
Yury Selivanov8be876e2018-09-11 17:10:37 -070049 ``(reader, writer)`` objects.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070050
51 The returned *reader* and *writer* objects are instances of
52 :class:`StreamReader` and :class:`StreamWriter` classes.
53
54 The *loop* argument is optional and can always be determined
55 automatically when this method is awaited from a coroutine.
56
57 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070058 returned :class:`StreamReader` instance. By default the *limit*
59 is set to 64 KiB.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010060
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040061 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070062 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010063
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040064 .. versionadded:: 3.7
65
66 The *ssl_handshake_timeout* parameter.
67
Yury Selivanov7c7605f2018-09-11 09:54:40 -070068.. coroutinefunction:: start_server(client_connected_cb, host=None, \
69 port=None, \*, loop=None, limit=None, \
70 family=socket.AF_UNSPEC, \
71 flags=socket.AI_PASSIVE, sock=None, \
72 backlog=100, ssl=None, reuse_address=None, \
73 reuse_port=None, ssl_handshake_timeout=None, \
74 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010075
Yury Selivanov7c7605f2018-09-11 09:54:40 -070076 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010077
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040078 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070079 connection is established. It receives a ``(reader, writer)`` pair
80 as two arguments, instances of the :class:`StreamReader` and
81 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010082
Yury Selivanov7c7605f2018-09-11 09:54:40 -070083 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040084 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Yury Selivanov7c7605f2018-09-11 09:54:40 -070085 it will be automatically wrapped into a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010086
Yury Selivanov7c7605f2018-09-11 09:54:40 -070087 The *loop* argument is optional and can always be determined
88 automatically when this method is awaited from a coroutine.
89
90 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070091 returned :class:`StreamReader` instance. By default the *limit*
92 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040093
94 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070095 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010096
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040097 .. versionadded:: 3.7
98
99 The *ssl_handshake_timeout* and *start_serving* parameters.
100
Yury Selivanov8be876e2018-09-11 17:10:37 -0700101
102.. rubric:: Unix Sockets
103
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700104.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
105 limit=None, ssl=None, sock=None, \
106 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500107
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700108 Establish a UNIX socket connection and return a pair of
109 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500110
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700111 Similar to :func:`open_connection` but operates on UNIX sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400112
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700113 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500114
115 Availability: UNIX.
116
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400117 .. versionadded:: 3.7
118
119 The *ssl_handshake_timeout* parameter.
120
121 .. versionchanged:: 3.7
122
123 The *path* parameter can now be a :term:`path-like object`
124
Yury Selivanov8be876e2018-09-11 17:10:37 -0700125
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700126.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
127 \*, loop=None, limit=None, sock=None, \
128 backlog=100, ssl=None, ssl_handshake_timeout=None, \
129 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500130
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700131 Start a UNIX socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500132
Yury Selivanov8be876e2018-09-11 17:10:37 -0700133 Similar to :func:`start_server` but works with UNIX sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400134
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700135 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500136
137 Availability: UNIX.
138
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400139 .. versionadded:: 3.7
140
141 The *ssl_handshake_timeout* and *start_serving* parameters.
142
143 .. versionchanged:: 3.7
144
145 The *path* parameter can now be a :term:`path-like object`.
146
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100147
Yury Selivanov8be876e2018-09-11 17:10:37 -0700148---------
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700149
150
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100151StreamReader
152============
153
Yury Selivanov8be876e2018-09-11 17:10:37 -0700154.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100155
Yury Selivanov8be876e2018-09-11 17:10:37 -0700156 Represents a reader object that provides APIs to read data
157 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100158
Yury Selivanov8be876e2018-09-11 17:10:37 -0700159 It is not recommended to instantiate *StreamReader* objects
160 directly; use :func:`open_connection` and :func:`start_server`
161 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100162
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100163 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100164
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500165 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
166 read until EOF and return all read bytes.
167
Yury Selivanov8be876e2018-09-11 17:10:37 -0700168 If an EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500169 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100170
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100171 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100172
Yury Selivanov8be876e2018-09-11 17:10:37 -0700173 Read one line, where "line" is a sequence of bytes
174 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500175
Yury Selivanov8be876e2018-09-11 17:10:37 -0700176 If an EOF is received and ``\n`` was not found, the method
177 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500178
Yury Selivanov8be876e2018-09-11 17:10:37 -0700179 If an EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500180 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100181
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100182 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100183
Yury Selivanov8be876e2018-09-11 17:10:37 -0700184 Read exactly *n* bytes.
185
186 Raise an :exc:`IncompleteReadError` if an EOF reached before *n*
187 can be read. Use the :attr:`IncompleteReadError.partial`
188 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100189
Berker Peksage5b0bd12016-10-18 00:34:46 +0300190 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400191
192 Read data from the stream until ``separator`` is found.
193
194 On success, the data and separator will be removed from the
195 internal buffer (consumed). Returned data will include the
196 separator at the end.
197
198 Configured stream limit is used to check result. Limit sets the
199 maximal length of data that can be returned, not counting the
200 separator.
201
202 If an EOF occurs and the complete separator is still not found,
203 an :exc:`IncompleteReadError` exception will be
204 raised, and the internal buffer will be reset. The
205 :attr:`IncompleteReadError.partial` attribute may contain the
206 separator partially.
207
208 If the data cannot be read because of over limit, a
209 :exc:`LimitOverrunError` exception will be raised, and the data
210 will be left in the internal buffer, so it can be read again.
211
212 .. versionadded:: 3.5.2
213
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500214 .. method:: at_eof()
215
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700216 Return ``True`` if the buffer is empty and :meth:`feed_eof`
217 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500218
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100219
220StreamWriter
221============
222
Yury Selivanov8be876e2018-09-11 17:10:37 -0700223.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100224
Yury Selivanov8be876e2018-09-11 17:10:37 -0700225 Represents a writer object that provides APIs to write data
226 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100227
Yury Selivanov8be876e2018-09-11 17:10:37 -0700228 It is not recommended to instantiate *StreamWriter* objects
229 directly; use :func:`open_connection` and :func:`start_server`
230 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100231
Yury Selivanov8be876e2018-09-11 17:10:37 -0700232 .. method:: write(data)
Victor Stinner83704962015-02-25 14:24:15 +0100233
Yury Selivanov8be876e2018-09-11 17:10:37 -0700234 Write *data* to the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100235
Yury Selivanov8be876e2018-09-11 17:10:37 -0700236 .. method:: writelines(data)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100237
Yury Selivanov8be876e2018-09-11 17:10:37 -0700238 Write a list (or any iterable) of bytes to the stream.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100239
Yury Selivanov8be876e2018-09-11 17:10:37 -0700240 .. coroutinemethod:: drain()
241
242 Wait until it is appropriate to resume writing to the stream.
243 E.g.::
244
245 writer.write(data)
246 await writer.drain()
247
248 This is a flow-control method that interacts with the underlying
249 IO write buffer. When the size of the buffer reaches
250 the high-water limit, *drain()* blocks until the size of the
251 buffer is drained down to the low-water limit and writing can
252 be resumed. When there is nothing to wait for, the :meth:`drain`
253 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100254
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100255 .. method:: close()
256
Yury Selivanov8be876e2018-09-11 17:10:37 -0700257 Close the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100258
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200259 .. method:: is_closing()
260
Yury Selivanov8be876e2018-09-11 17:10:37 -0700261 Return ``True`` if the stream is closed or in the process of
262 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200263
264 .. versionadded:: 3.7
265
266 .. coroutinemethod:: wait_closed()
267
Yury Selivanov8be876e2018-09-11 17:10:37 -0700268 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200269
Yury Selivanov8be876e2018-09-11 17:10:37 -0700270 Should be called after :meth:`close` to wait until the underlying
271 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200272
273 .. versionadded:: 3.7
274
Yury Selivanov8be876e2018-09-11 17:10:37 -0700275 .. method:: can_write_eof()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100276
Yury Selivanov8be876e2018-09-11 17:10:37 -0700277 Return *True* if the underlying transport supports
278 the :meth:`write_eof` method, *False* otherwise.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100279
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100280 .. method:: write_eof()
281
Yury Selivanov8be876e2018-09-11 17:10:37 -0700282 Close the write end of the stream after the buffered write
283 data is flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100284
Yury Selivanov8be876e2018-09-11 17:10:37 -0700285 .. attribute:: transport
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100286
Yury Selivanov8be876e2018-09-11 17:10:37 -0700287 Return the underlying asyncio transport.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100288
Yury Selivanov8be876e2018-09-11 17:10:37 -0700289 .. method:: get_extra_info(name, default=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100290
Yury Selivanov8be876e2018-09-11 17:10:37 -0700291 Access optional transport information; see
292 :meth:`BaseTransport.get_extra_info` for details.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100293
Victor Stinnerc520edc2014-01-23 11:25:48 +0100294
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700295Examples
296========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200297
Victor Stinnered051592014-10-12 20:18:16 +0200298.. _asyncio-tcp-echo-client-streams:
299
300TCP echo client using streams
301-----------------------------
302
303TCP echo client using the :func:`asyncio.open_connection` function::
304
305 import asyncio
306
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700307 async def tcp_echo_client(message):
308 reader, writer = await asyncio.open_connection(
309 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200310
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700311 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200312 writer.write(message.encode())
313
Andrew Svetlov88743422017-12-11 17:35:49 +0200314 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700315 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200316
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700317 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200318 writer.close()
319
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700320 asyncio.run(tcp_echo_client('Hello World!'))
321
Victor Stinnered051592014-10-12 20:18:16 +0200322
323.. seealso::
324
325 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700326 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200327
328
329.. _asyncio-tcp-echo-server-streams:
330
331TCP echo server using streams
332-----------------------------
333
334TCP echo server using the :func:`asyncio.start_server` function::
335
336 import asyncio
337
Andrew Svetlov88743422017-12-11 17:35:49 +0200338 async def handle_echo(reader, writer):
339 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200340 message = data.decode()
341 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200342
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700343 print(f"Received {message!r} from {addr!r}")
344
345 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200346 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200347 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200348
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700349 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200350 writer.close()
351
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700352 async def main():
353 server = await asyncio.start_server(
354 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200355
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700356 addr = server.sockets[0].getsockname()
357 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200358
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700359 async with server:
360 await server.serve_forever()
361
362 asyncio.run(main())
363
Victor Stinnered051592014-10-12 20:18:16 +0200364
365.. seealso::
366
367 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200369
370
Victor Stinner5121a9b2014-10-11 15:52:14 +0200371Get HTTP headers
372----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100373
374Simple example querying HTTP headers of the URL passed on the command line::
375
376 import asyncio
377 import urllib.parse
378 import sys
379
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400380 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100381 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200382 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700383 reader, writer = await asyncio.open_connection(
384 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200385 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700386 reader, writer = await asyncio.open_connection(
387 url.hostname, 80)
388
389 query = (
390 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
391 f"Host: {url.hostname}\r\n"
392 f"\r\n"
393 )
394
Victor Stinnerc520edc2014-01-23 11:25:48 +0100395 writer.write(query.encode('latin-1'))
396 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200397 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100398 if not line:
399 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700400
Victor Stinnerc520edc2014-01-23 11:25:48 +0100401 line = line.decode('latin1').rstrip()
402 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700403 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100404
Victor Stinner5121a9b2014-10-11 15:52:14 +0200405 # Ignore the body, close the socket
406 writer.close()
407
Victor Stinnerc520edc2014-01-23 11:25:48 +0100408 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700409 asyncio.run(print_http_headers(url))
410
Victor Stinnerc520edc2014-01-23 11:25:48 +0100411
412Usage::
413
414 python example.py http://example.com/path/page.html
415
Victor Stinner04e6df32014-10-11 16:16:27 +0200416or with HTTPS::
417
418 python example.py https://example.com/path/page.html
419
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700420
Victor Stinner04e6df32014-10-11 16:16:27 +0200421.. _asyncio-register-socket-streams:
422
423Register an open socket to wait for data using streams
424------------------------------------------------------
425
426Coroutine waiting until a socket receives data using the
427:func:`open_connection` function::
428
429 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700430 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200431
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700432 async def wait_for_data():
433 # Get a reference to the current event loop because
434 # we want to access low-level APIs.
435 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200436
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700437 # Create a pair of connected sockets.
438 rsock, wsock = socket.socketpair()
439
440 # Register the open socket to wait for data.
441 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200442
443 # Simulate the reception of data from the network
444 loop.call_soon(wsock.send, 'abc'.encode())
445
446 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200447 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200448
449 # Got data, we are done: close the socket
450 print("Received:", data.decode())
451 writer.close()
452
453 # Close the second socket
454 wsock.close()
455
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700456 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200457
458.. seealso::
459
460 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700461 <asyncio-register-socket>` example uses a low-level protocol and
462 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200463
464 The :ref:`watch a file descriptor for read events
465 <asyncio-watch-read-event>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700466 :meth:`loop.add_reader` method to watch a file descriptor.