blob: 80b76253d0656953c3daec32e808468af4d7f3a9 [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}')
Andrew Svetlov11194c82018-09-13 16:53:49 -070023 await writer.awrite(message.encode())
Yury Selivanov7c7605f2018-09-11 09:54:40 -070024
25 data = await reader.read(100)
26 print(f'Received: {data.decode()!r}')
27
28 print('Close the connection')
Andrew Svetlov11194c82018-09-13 16:53:49 -070029 await writer.aclose()
Yury Selivanov7c7605f2018-09-11 09:54:40 -070030
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
Andrew Svetlov11194c82018-09-13 16:53:49 -0700232 .. coroutinemethod:: awrite(data)
233
234 Write *data* to the stream.
235
236 The method respects control-flow, execution is paused if write
237 buffer reaches high-water limit.
238
239 .. versionadded:: 3.8
240
241 .. coroutinemethod:: aclose()
242
243 Close the stream.
244
245 Wait for finishing all closing actions, e.g. SSL shutdown for
246 secure sockets.
247
248 .. versionadded:: 3.8
249
250 .. method:: can_write_eof()
251
252 Return *True* if the underlying transport supports
253 the :meth:`write_eof` method, *False* otherwise.
254
255 .. method:: write_eof()
256
257 Close the write end of the stream after the buffered write
258 data is flushed.
259
260 .. attribute:: transport
261
262 Return the underlying asyncio transport.
263
264 .. method:: get_extra_info(name, default=None)
265
266 Access optional transport information; see
267 :meth:`BaseTransport.get_extra_info` for details.
268
Yury Selivanov8be876e2018-09-11 17:10:37 -0700269 .. method:: write(data)
Victor Stinner83704962015-02-25 14:24:15 +0100270
Yury Selivanov8be876e2018-09-11 17:10:37 -0700271 Write *data* to the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100272
Andrew Svetlov11194c82018-09-13 16:53:49 -0700273 This method doesn't apply control-flow. The call should be
274 followed by :meth:`drain`.
275
Yury Selivanov8be876e2018-09-11 17:10:37 -0700276 .. method:: writelines(data)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100277
Yury Selivanov8be876e2018-09-11 17:10:37 -0700278 Write a list (or any iterable) of bytes to the stream.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100279
Andrew Svetlov11194c82018-09-13 16:53:49 -0700280 This method doesn't apply control-flow. The call should be
281 followed by :meth:`drain`.
282
Yury Selivanov8be876e2018-09-11 17:10:37 -0700283 .. coroutinemethod:: drain()
284
285 Wait until it is appropriate to resume writing to the stream.
286 E.g.::
287
288 writer.write(data)
289 await writer.drain()
290
291 This is a flow-control method that interacts with the underlying
292 IO write buffer. When the size of the buffer reaches
293 the high-water limit, *drain()* blocks until the size of the
294 buffer is drained down to the low-water limit and writing can
295 be resumed. When there is nothing to wait for, the :meth:`drain`
296 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100297
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100298 .. method:: close()
299
Yury Selivanov8be876e2018-09-11 17:10:37 -0700300 Close the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100301
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200302 .. method:: is_closing()
303
Yury Selivanov8be876e2018-09-11 17:10:37 -0700304 Return ``True`` if the stream is closed or in the process of
305 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200306
307 .. versionadded:: 3.7
308
309 .. coroutinemethod:: wait_closed()
310
Yury Selivanov8be876e2018-09-11 17:10:37 -0700311 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200312
Yury Selivanov8be876e2018-09-11 17:10:37 -0700313 Should be called after :meth:`close` to wait until the underlying
314 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200315
316 .. versionadded:: 3.7
317
Victor Stinnerc520edc2014-01-23 11:25:48 +0100318
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700319Examples
320========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200321
Victor Stinnered051592014-10-12 20:18:16 +0200322.. _asyncio-tcp-echo-client-streams:
323
324TCP echo client using streams
325-----------------------------
326
327TCP echo client using the :func:`asyncio.open_connection` function::
328
329 import asyncio
330
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700331 async def tcp_echo_client(message):
332 reader, writer = await asyncio.open_connection(
333 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200334
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700335 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200336 writer.write(message.encode())
337
Andrew Svetlov88743422017-12-11 17:35:49 +0200338 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700339 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200340
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700341 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200342 writer.close()
343
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700344 asyncio.run(tcp_echo_client('Hello World!'))
345
Victor Stinnered051592014-10-12 20:18:16 +0200346
347.. seealso::
348
349 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700350 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200351
352
353.. _asyncio-tcp-echo-server-streams:
354
355TCP echo server using streams
356-----------------------------
357
358TCP echo server using the :func:`asyncio.start_server` function::
359
360 import asyncio
361
Andrew Svetlov88743422017-12-11 17:35:49 +0200362 async def handle_echo(reader, writer):
363 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200364 message = data.decode()
365 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200366
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700367 print(f"Received {message!r} from {addr!r}")
368
369 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200370 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200371 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200372
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700373 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200374 writer.close()
375
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700376 async def main():
377 server = await asyncio.start_server(
378 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200379
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700380 addr = server.sockets[0].getsockname()
381 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200382
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700383 async with server:
384 await server.serve_forever()
385
386 asyncio.run(main())
387
Victor Stinnered051592014-10-12 20:18:16 +0200388
389.. seealso::
390
391 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700392 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200393
394
Victor Stinner5121a9b2014-10-11 15:52:14 +0200395Get HTTP headers
396----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100397
398Simple example querying HTTP headers of the URL passed on the command line::
399
400 import asyncio
401 import urllib.parse
402 import sys
403
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400404 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100405 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200406 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700407 reader, writer = await asyncio.open_connection(
408 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200409 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700410 reader, writer = await asyncio.open_connection(
411 url.hostname, 80)
412
413 query = (
414 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
415 f"Host: {url.hostname}\r\n"
416 f"\r\n"
417 )
418
Victor Stinnerc520edc2014-01-23 11:25:48 +0100419 writer.write(query.encode('latin-1'))
420 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200421 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100422 if not line:
423 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700424
Victor Stinnerc520edc2014-01-23 11:25:48 +0100425 line = line.decode('latin1').rstrip()
426 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700427 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100428
Victor Stinner5121a9b2014-10-11 15:52:14 +0200429 # Ignore the body, close the socket
430 writer.close()
431
Victor Stinnerc520edc2014-01-23 11:25:48 +0100432 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700433 asyncio.run(print_http_headers(url))
434
Victor Stinnerc520edc2014-01-23 11:25:48 +0100435
436Usage::
437
438 python example.py http://example.com/path/page.html
439
Victor Stinner04e6df32014-10-11 16:16:27 +0200440or with HTTPS::
441
442 python example.py https://example.com/path/page.html
443
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700444
Victor Stinner04e6df32014-10-11 16:16:27 +0200445.. _asyncio-register-socket-streams:
446
447Register an open socket to wait for data using streams
448------------------------------------------------------
449
450Coroutine waiting until a socket receives data using the
451:func:`open_connection` function::
452
453 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700454 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200455
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700456 async def wait_for_data():
457 # Get a reference to the current event loop because
458 # we want to access low-level APIs.
459 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200460
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700461 # Create a pair of connected sockets.
462 rsock, wsock = socket.socketpair()
463
464 # Register the open socket to wait for data.
465 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200466
467 # Simulate the reception of data from the network
468 loop.call_soon(wsock.send, 'abc'.encode())
469
470 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200471 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200472
473 # Got data, we are done: close the socket
474 print("Received:", data.decode())
475 writer.close()
476
477 # Close the second socket
478 wsock.close()
479
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700480 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200481
482.. seealso::
483
484 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700485 <asyncio-register-socket>` example uses a low-level protocol and
486 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200487
488 The :ref:`watch a file descriptor for read events
489 <asyncio-watch-read-event>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700490 :meth:`loop.add_reader` method to watch a file descriptor.