blob: 3fe7ac7b4abc683f9ab1d74864bacdc18a381334 [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
10network connections. Streams allow send and receive data without
11using callbacks or low-level protocols and transports.
lf627d2c82017-07-25 17:03:51 -060012
Yury Selivanov7c7605f2018-09-11 09:54:40 -070013Here's an example of a TCP echo client written using asyncio
14streams::
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 Selivanov7c7605f2018-09-11 09:54:40 -070034.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010035
Yury Selivanov7c7605f2018-09-11 09:54:40 -070036The following top-level asyncio functions can be used to create
37and work with streams:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010038
Victor Stinner24f8ebf2014-01-23 11:05:01 +010039
Yury Selivanov7c7605f2018-09-11 09:54:40 -070040.. coroutinefunction:: open_connection(host=None, port=None, \*, \
41 loop=None, limit=None, ssl=None, family=0, \
42 proto=0, flags=0, sock=None, local_addr=None, \
43 server_hostname=None, ssl_handshake_timeout=None)
44
45 Establish a network connection and return a pair of
46 ``(reader, writer)``.
47
48 The returned *reader* and *writer* objects are instances of
49 :class:`StreamReader` and :class:`StreamWriter` classes.
50
51 The *loop* argument is optional and can always be determined
52 automatically when this method is awaited from a coroutine.
53
54 *limit* determines the buffer size limit used by the
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040055 returned :class:`StreamReader` instance.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010056
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040057 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070058 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010059
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040060 .. versionadded:: 3.7
61
62 The *ssl_handshake_timeout* parameter.
63
Yury Selivanov7c7605f2018-09-11 09:54:40 -070064.. coroutinefunction:: start_server(client_connected_cb, host=None, \
65 port=None, \*, loop=None, limit=None, \
66 family=socket.AF_UNSPEC, \
67 flags=socket.AI_PASSIVE, sock=None, \
68 backlog=100, ssl=None, reuse_address=None, \
69 reuse_port=None, ssl_handshake_timeout=None, \
70 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010071
Yury Selivanov7c7605f2018-09-11 09:54:40 -070072 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010073
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040074 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070075 connection is established. It receives a ``(reader, writer)`` pair
76 as two arguments, instances of the :class:`StreamReader` and
77 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010078
Yury Selivanov7c7605f2018-09-11 09:54:40 -070079 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040080 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Yury Selivanov7c7605f2018-09-11 09:54:40 -070081 it will be automatically wrapped into a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010082
Yury Selivanov7c7605f2018-09-11 09:54:40 -070083 The *loop* argument is optional and can always be determined
84 automatically when this method is awaited from a coroutine.
85
86 *limit* determines the buffer size limit used by the
87 returned :class:`StreamReader` instance.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040088
89 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070090 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010091
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040092 .. versionadded:: 3.7
93
94 The *ssl_handshake_timeout* and *start_serving* parameters.
95
Yury Selivanov7c7605f2018-09-11 09:54:40 -070096.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
97 limit=None, ssl=None, sock=None, \
98 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050099
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700100 Establish a UNIX socket connection and return a pair of
101 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500102
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700103 Similar to :func:`open_connection` but operates on UNIX sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400104
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700105 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500106
107 Availability: UNIX.
108
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400109 .. versionadded:: 3.7
110
111 The *ssl_handshake_timeout* parameter.
112
113 .. versionchanged:: 3.7
114
115 The *path* parameter can now be a :term:`path-like object`
116
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700117.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
118 \*, loop=None, limit=None, sock=None, \
119 backlog=100, ssl=None, ssl_handshake_timeout=None, \
120 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500121
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700122 Start a UNIX socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500123
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700124 Similar to :func:`start_server` but operates on UNIX sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400125
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700126 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500127
128 Availability: UNIX.
129
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400130 .. versionadded:: 3.7
131
132 The *ssl_handshake_timeout* and *start_serving* parameters.
133
134 .. versionchanged:: 3.7
135
136 The *path* parameter can now be a :term:`path-like object`.
137
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100138
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700139.. rubric:: Contents
140
141* `StreamReader`_ and `StreamWriter`_
142* `StreamReaderProtocol`_
143* `Examples`_
144
145
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100146StreamReader
147============
148
Victor Stinner08444382014-02-02 22:43:39 +0100149.. class:: StreamReader(limit=None, loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100150
Victor Stinner83704962015-02-25 14:24:15 +0100151 This class is :ref:`not thread safe <asyncio-multithreading>`.
152
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100153 .. method:: exception()
154
155 Get the exception.
156
157 .. method:: feed_eof()
158
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500159 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100160
161 .. method:: feed_data(data)
162
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500163 Feed *data* bytes in the internal buffer. Any operations waiting
164 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
166 .. method:: set_exception(exc)
167
168 Set the exception.
169
170 .. method:: set_transport(transport)
171
172 Set the transport.
173
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100174 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100175
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500176 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
177 read until EOF and return all read bytes.
178
179 If the EOF was received and the internal buffer is empty,
180 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100181
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100182 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100183
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500184 Read one line, where "line" is a sequence of bytes ending with ``\n``.
185
186 If EOF is received, and ``\n`` was not found, the method will
187 return the partial read bytes.
188
189 If the EOF was received and the internal buffer is empty,
190 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100191
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100192 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100193
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100194 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
195 the stream is reached before *n* can be read, the
196 :attr:`IncompleteReadError.partial` attribute of the exception contains
197 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100198
Berker Peksage5b0bd12016-10-18 00:34:46 +0300199 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400200
201 Read data from the stream until ``separator`` is found.
202
203 On success, the data and separator will be removed from the
204 internal buffer (consumed). Returned data will include the
205 separator at the end.
206
207 Configured stream limit is used to check result. Limit sets the
208 maximal length of data that can be returned, not counting the
209 separator.
210
211 If an EOF occurs and the complete separator is still not found,
212 an :exc:`IncompleteReadError` exception will be
213 raised, and the internal buffer will be reset. The
214 :attr:`IncompleteReadError.partial` attribute may contain the
215 separator partially.
216
217 If the data cannot be read because of over limit, a
218 :exc:`LimitOverrunError` exception will be raised, and the data
219 will be left in the internal buffer, so it can be read again.
220
221 .. versionadded:: 3.5.2
222
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500223 .. method:: at_eof()
224
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700225 Return ``True`` if the buffer is empty and :meth:`feed_eof`
226 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500227
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100228
229StreamWriter
230============
231
232.. class:: StreamWriter(transport, protocol, reader, loop)
233
234 Wraps a Transport.
235
236 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
237 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
238 :meth:`drain` which returns an optional :class:`Future` on which you can
239 wait for flow control. It also adds a transport attribute which references
240 the :class:`Transport` directly.
241
Victor Stinner83704962015-02-25 14:24:15 +0100242 This class is :ref:`not thread safe <asyncio-multithreading>`.
243
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100244 .. attribute:: transport
245
246 Transport.
247
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100248 .. method:: can_write_eof()
249
250 Return :const:`True` if the transport supports :meth:`write_eof`,
251 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
252
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100253 .. method:: close()
254
255 Close the transport: see :meth:`BaseTransport.close`.
256
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200257 .. method:: is_closing()
258
259 Return ``True`` if the writer is closing or is closed.
260
261 .. versionadded:: 3.7
262
263 .. coroutinemethod:: wait_closed()
264
265 Wait until the writer is closed.
266
267 Should be called after :meth:`close` to wait until the underlying
268 connection (and the associated transport/protocol pair) is closed.
269
270 .. versionadded:: 3.7
271
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100272 .. coroutinemethod:: drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100273
Victor Stinnere7182972014-11-28 17:45:41 +0100274 Let the write buffer of the underlying transport a chance to be flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100275
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200276 The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100277
278 w.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200279 await w.drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100280
Victor Stinnere7182972014-11-28 17:45:41 +0100281 When the size of the transport buffer reaches the high-water limit (the
282 protocol is paused), block until the size of the buffer is drained down
283 to the low-water limit and the protocol is resumed. When there is nothing
284 to wait for, the yield-from continues immediately.
285
286 Yielding from :meth:`drain` gives the opportunity for the loop to
287 schedule the write operation and flush the buffer. It should especially
288 be used when a possibly large amount of data is written to the transport,
289 and the coroutine does not yield-from between calls to :meth:`write`.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200290
291 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100292
293 .. method:: get_extra_info(name, default=None)
294
295 Return optional transport information: see
296 :meth:`BaseTransport.get_extra_info`.
297
298 .. method:: write(data)
299
300 Write some *data* bytes to the transport: see
301 :meth:`WriteTransport.write`.
302
303 .. method:: writelines(data)
304
305 Write a list (or any iterable) of data bytes to the transport:
306 see :meth:`WriteTransport.writelines`.
307
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100308 .. method:: write_eof()
309
310 Close the write end of the transport after flushing buffered data:
311 see :meth:`WriteTransport.write_eof`.
312
313
314StreamReaderProtocol
315====================
316
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700317.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, \
318 loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100319
320 Trivial helper class to adapt between :class:`Protocol` and
Jesus Ceaded4c492016-04-19 21:50:19 +0200321 :class:`StreamReader`. Subclass of :class:`Protocol`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100322
323 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
324 is an optional function called with (stream_reader, stream_writer) when a
325 connection is made, *loop* is the event loop instance to use.
326
327 (This is a helper class instead of making :class:`StreamReader` itself a
328 :class:`Protocol` subclass, because the :class:`StreamReader` has other
R David Murray87d00662015-09-27 12:36:19 -0400329 potential uses, and to prevent the user of the :class:`StreamReader` from
330 accidentally calling inappropriate methods of the protocol.)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100331
Victor Stinnerc520edc2014-01-23 11:25:48 +0100332
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700333Examples
334========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200335
Victor Stinnered051592014-10-12 20:18:16 +0200336.. _asyncio-tcp-echo-client-streams:
337
338TCP echo client using streams
339-----------------------------
340
341TCP echo client using the :func:`asyncio.open_connection` function::
342
343 import asyncio
344
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700345 async def tcp_echo_client(message):
346 reader, writer = await asyncio.open_connection(
347 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200348
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700349 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200350 writer.write(message.encode())
351
Andrew Svetlov88743422017-12-11 17:35:49 +0200352 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700353 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200354
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700355 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200356 writer.close()
357
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700358 asyncio.run(tcp_echo_client('Hello World!'))
359
Victor Stinnered051592014-10-12 20:18:16 +0200360
361.. seealso::
362
363 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700364 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200365
366
367.. _asyncio-tcp-echo-server-streams:
368
369TCP echo server using streams
370-----------------------------
371
372TCP echo server using the :func:`asyncio.start_server` function::
373
374 import asyncio
375
Andrew Svetlov88743422017-12-11 17:35:49 +0200376 async def handle_echo(reader, writer):
377 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200378 message = data.decode()
379 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200380
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700381 print(f"Received {message!r} from {addr!r}")
382
383 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200384 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200385 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200386
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700387 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200388 writer.close()
389
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700390 async def main():
391 server = await asyncio.start_server(
392 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200393
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700394 addr = server.sockets[0].getsockname()
395 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200396
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700397 async with server:
398 await server.serve_forever()
399
400 asyncio.run(main())
401
Victor Stinnered051592014-10-12 20:18:16 +0200402
403.. seealso::
404
405 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700406 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200407
408
Victor Stinner5121a9b2014-10-11 15:52:14 +0200409Get HTTP headers
410----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100411
412Simple example querying HTTP headers of the URL passed on the command line::
413
414 import asyncio
415 import urllib.parse
416 import sys
417
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400418 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100419 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200420 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700421 reader, writer = await asyncio.open_connection(
422 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200423 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700424 reader, writer = await asyncio.open_connection(
425 url.hostname, 80)
426
427 query = (
428 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
429 f"Host: {url.hostname}\r\n"
430 f"\r\n"
431 )
432
Victor Stinnerc520edc2014-01-23 11:25:48 +0100433 writer.write(query.encode('latin-1'))
434 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200435 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100436 if not line:
437 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700438
Victor Stinnerc520edc2014-01-23 11:25:48 +0100439 line = line.decode('latin1').rstrip()
440 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700441 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100442
Victor Stinner5121a9b2014-10-11 15:52:14 +0200443 # Ignore the body, close the socket
444 writer.close()
445
Victor Stinnerc520edc2014-01-23 11:25:48 +0100446 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700447 asyncio.run(print_http_headers(url))
448
Victor Stinnerc520edc2014-01-23 11:25:48 +0100449
450Usage::
451
452 python example.py http://example.com/path/page.html
453
Victor Stinner04e6df32014-10-11 16:16:27 +0200454or with HTTPS::
455
456 python example.py https://example.com/path/page.html
457
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700458
Victor Stinner04e6df32014-10-11 16:16:27 +0200459.. _asyncio-register-socket-streams:
460
461Register an open socket to wait for data using streams
462------------------------------------------------------
463
464Coroutine waiting until a socket receives data using the
465:func:`open_connection` function::
466
467 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700468 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200469
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700470 async def wait_for_data():
471 # Get a reference to the current event loop because
472 # we want to access low-level APIs.
473 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200474
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700475 # Create a pair of connected sockets.
476 rsock, wsock = socket.socketpair()
477
478 # Register the open socket to wait for data.
479 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200480
481 # Simulate the reception of data from the network
482 loop.call_soon(wsock.send, 'abc'.encode())
483
484 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200485 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200486
487 # Got data, we are done: close the socket
488 print("Received:", data.decode())
489 writer.close()
490
491 # Close the second socket
492 wsock.close()
493
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700494 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200495
496.. seealso::
497
498 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700499 <asyncio-register-socket>` example uses a low-level protocol and
500 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200501
502 The :ref:`watch a file descriptor for read events
503 <asyncio-watch-read-event>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700504 :meth:`loop.add_reader` method to watch a file descriptor.