blob: 42b4c1f76d3e74d166538fc28d409ac4ac9cb523 [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 Selivanov512d7102018-09-17 19:35:30 -04005=======
6Streams
7=======
Victor Stinner24f8ebf2014-01-23 11:05:01 +01008
Yury Selivanov512d7102018-09-17 19:35:30 -04009Streams are high-level async/await-ready primitives to work with
10network connections. Streams allow sending and receiving data without
11using callbacks or low-level protocols and transports.
lf627d2c82017-07-25 17:03:51 -060012
Yury Selivanov512d7102018-09-17 19:35:30 -040013.. _asyncio_example_stream:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010014
Yury Selivanov512d7102018-09-17 19:35:30 -040015Here is an example of a TCP echo client written using asyncio
16streams::
Guido van Rossum19ff6972015-10-19 13:18:04 -070017
Yury Selivanov512d7102018-09-17 19:35:30 -040018 import asyncio
19
20 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}')
25 writer.write(message.encode())
26
27 data = await reader.read(100)
28 print(f'Received: {data.decode()!r}')
29
30 print('Close the connection')
31 writer.close()
32 await writer.wait_closed()
33
34 asyncio.run(tcp_echo_client('Hello World!'))
Guido van Rossum19ff6972015-10-19 13:18:04 -070035
36
Yury Selivanov512d7102018-09-17 19:35:30 -040037See also the `Examples`_ section below.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010038
Victor Stinner24f8ebf2014-01-23 11:05:01 +010039
Yury Selivanov512d7102018-09-17 19:35:30 -040040.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010041
Yury Selivanov512d7102018-09-17 19:35:30 -040042The following top-level asyncio functions can be used to create
43and work with streams:
44
45
46.. coroutinefunction:: open_connection(host=None, port=None, \*, \
47 loop=None, limit=None, ssl=None, family=0, \
48 proto=0, flags=0, sock=None, local_addr=None, \
49 server_hostname=None, ssl_handshake_timeout=None)
50
51 Establish a network connection and return a pair of
52 ``(reader, writer)`` objects.
53
54 The returned *reader* and *writer* objects are instances of
55 :class:`StreamReader` and :class:`StreamWriter` classes.
56
57 The *loop* argument is optional and can always be determined
58 automatically when this function is awaited from a coroutine.
59
60 *limit* determines the buffer size limit used by the
61 returned :class:`StreamReader` instance. By default the *limit*
62 is set to 64 KiB.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010063
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070064 The rest of the arguments are passed directly to
Yury Selivanov512d7102018-09-17 19:35:30 -040065 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010066
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070067 .. versionadded:: 3.7
68
69 The *ssl_handshake_timeout* parameter.
70
Yury Selivanov512d7102018-09-17 19:35:30 -040071.. coroutinefunction:: start_server(client_connected_cb, host=None, \
72 port=None, \*, loop=None, limit=None, \
73 family=socket.AF_UNSPEC, \
74 flags=socket.AI_PASSIVE, sock=None, \
75 backlog=100, ssl=None, reuse_address=None, \
76 reuse_port=None, ssl_handshake_timeout=None, \
77 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010078
Yury Selivanov512d7102018-09-17 19:35:30 -040079 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010080
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070081 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov512d7102018-09-17 19:35:30 -040082 connection is established. It receives a ``(reader, writer)`` pair
83 as two arguments, instances of the :class:`StreamReader` and
84 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010085
Yury Selivanov512d7102018-09-17 19:35:30 -040086 *client_connected_cb* can be a plain callable or a
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070087 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Yury Selivanov512d7102018-09-17 19:35:30 -040088 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010089
Yury Selivanov512d7102018-09-17 19:35:30 -040090 The *loop* argument is optional and can always be determined
91 automatically when this method is awaited from a coroutine.
92
93 *limit* determines the buffer size limit used by the
94 returned :class:`StreamReader` instance. By default the *limit*
95 is set to 64 KiB.
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070096
97 The rest of the arguments are passed directly to
Yury Selivanov512d7102018-09-17 19:35:30 -040098 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010099
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700100 .. versionadded:: 3.7
101
102 The *ssl_handshake_timeout* and *start_serving* parameters.
103
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500104
Yury Selivanov512d7102018-09-17 19:35:30 -0400105.. rubric:: Unix Sockets
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500106
Yury Selivanov512d7102018-09-17 19:35:30 -0400107.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
108 limit=None, ssl=None, sock=None, \
109 server_hostname=None, ssl_handshake_timeout=None)
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700110
Yury Selivanov512d7102018-09-17 19:35:30 -0400111 Establish a Unix socket connection and return a pair of
112 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500113
Yury Selivanov512d7102018-09-17 19:35:30 -0400114 Similar to :func:`open_connection` but operates on Unix sockets.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500115
Yury Selivanov512d7102018-09-17 19:35:30 -0400116 See also the documentation of :meth:`loop.create_unix_connection`.
117
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400118 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500119
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700120 .. versionadded:: 3.7
121
122 The *ssl_handshake_timeout* parameter.
123
124 .. versionchanged:: 3.7
125
126 The *path* parameter can now be a :term:`path-like object`
127
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500128
Yury Selivanov512d7102018-09-17 19:35:30 -0400129.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
130 \*, loop=None, limit=None, sock=None, \
131 backlog=100, ssl=None, ssl_handshake_timeout=None, \
132 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500133
Yury Selivanov512d7102018-09-17 19:35:30 -0400134 Start a Unix socket server.
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700135
Yury Selivanov512d7102018-09-17 19:35:30 -0400136 Similar to :func:`start_server` but works with Unix sockets.
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700137
Yury Selivanov512d7102018-09-17 19:35:30 -0400138 See also the documentation of :meth:`loop.create_unix_server`.
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700139
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400140 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500141
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700142 .. versionadded:: 3.7
143
144 The *ssl_handshake_timeout* and *start_serving* parameters.
145
146 .. versionchanged:: 3.7
147
148 The *path* parameter can now be a :term:`path-like object`.
149
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100150
Yury Selivanov512d7102018-09-17 19:35:30 -0400151---------
152
153
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100154StreamReader
155============
156
Yury Selivanov512d7102018-09-17 19:35:30 -0400157.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100158
Yury Selivanov512d7102018-09-17 19:35:30 -0400159 Represents a reader object that provides APIs to read data
160 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100161
Yury Selivanov512d7102018-09-17 19:35:30 -0400162 It is not recommended to instantiate *StreamReader* objects
163 directly; use :func:`open_connection` and :func:`start_server`
164 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100166 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100167
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500168 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
169 read until EOF and return all read bytes.
170
Yury Selivanov512d7102018-09-17 19:35:30 -0400171 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500172 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100173
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100174 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100175
Yury Selivanov512d7102018-09-17 19:35:30 -0400176 Read one line, where "line" is a sequence of bytes
177 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500178
Yury Selivanov512d7102018-09-17 19:35:30 -0400179 If EOF is received and ``\n`` was not found, the method
180 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500181
Yury Selivanov512d7102018-09-17 19:35:30 -0400182 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500183 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100184
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100185 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100186
Yury Selivanov512d7102018-09-17 19:35:30 -0400187 Read exactly *n* bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100188
Yury Selivanov512d7102018-09-17 19:35:30 -0400189 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
190 can be read. Use the :attr:`IncompleteReadError.partial`
191 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100192
Berker Peksage5b0bd12016-10-18 00:34:46 +0300193 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400194
Yury Selivanov512d7102018-09-17 19:35:30 -0400195 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400196
197 On success, the data and separator will be removed from the
198 internal buffer (consumed). Returned data will include the
199 separator at the end.
200
Yury Selivanov512d7102018-09-17 19:35:30 -0400201 If the amount of data read exceeds the configured stream limit, a
202 :exc:`LimitOverrunError` exception is raised, and the data
203 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400204
Yury Selivanov512d7102018-09-17 19:35:30 -0400205 If EOF is reached before the complete separator is found,
206 an :exc:`IncompleteReadError` exception is raised, and the internal
207 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
208 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400209
210 .. versionadded:: 3.5.2
211
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500212 .. method:: at_eof()
213
Yury Selivanov512d7102018-09-17 19:35:30 -0400214 Return ``True`` if the buffer is empty and :meth:`feed_eof`
215 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500216
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100217
218StreamWriter
219============
220
Yury Selivanov512d7102018-09-17 19:35:30 -0400221.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100222
Yury Selivanov512d7102018-09-17 19:35:30 -0400223 Represents a writer object that provides APIs to write data
224 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100225
Yury Selivanov512d7102018-09-17 19:35:30 -0400226 It is not recommended to instantiate *StreamWriter* objects
227 directly; use :func:`open_connection` and :func:`start_server`
228 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100229
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100230 .. method:: can_write_eof()
231
Yury Selivanov512d7102018-09-17 19:35:30 -0400232 Return *True* if the underlying transport supports
233 the :meth:`write_eof` method, *False* otherwise.
234
235 .. method:: write_eof()
236
237 Close the write end of the stream after the buffered write
238 data is flushed.
239
240 .. attribute:: transport
241
242 Return the underlying asyncio transport.
243
244 .. method:: get_extra_info(name, default=None)
245
246 Access optional transport information; see
247 :meth:`BaseTransport.get_extra_info` for details.
248
249 .. method:: write(data)
250
251 Write *data* to the stream.
252
253 This method is not subject to flow control. Calls to ``write()`` should
254 be followed by :meth:`drain`.
255
256 .. method:: writelines(data)
257
258 Write a list (or any iterable) of bytes to the stream.
259
260 This method is not subject to flow control. Calls to ``writelines()``
261 should be followed by :meth:`drain`.
262
263 .. coroutinemethod:: drain()
264
265 Wait until it is appropriate to resume writing to the stream.
266 Example::
267
268 writer.write(data)
269 await writer.drain()
270
271 This is a flow control method that interacts with the underlying
272 IO write buffer. When the size of the buffer reaches
273 the high watermark, *drain()* blocks until the size of the
274 buffer is drained down to the low watermark and writing can
275 be resumed. When there is nothing to wait for, the :meth:`drain`
276 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100277
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100278 .. method:: close()
279
Yury Selivanov512d7102018-09-17 19:35:30 -0400280 Close the stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100281
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200282 .. method:: is_closing()
283
Yury Selivanov512d7102018-09-17 19:35:30 -0400284 Return ``True`` if the stream is closed or in the process of
285 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200286
287 .. versionadded:: 3.7
288
289 .. coroutinemethod:: wait_closed()
290
Yury Selivanov512d7102018-09-17 19:35:30 -0400291 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200292
Yury Selivanov512d7102018-09-17 19:35:30 -0400293 Should be called after :meth:`close` to wait until the underlying
294 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200295
296 .. versionadded:: 3.7
297
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100298
Yury Selivanov512d7102018-09-17 19:35:30 -0400299Examples
300========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200301
Victor Stinnered051592014-10-12 20:18:16 +0200302.. _asyncio-tcp-echo-client-streams:
303
304TCP echo client using streams
305-----------------------------
306
307TCP echo client using the :func:`asyncio.open_connection` function::
308
309 import asyncio
310
Yury Selivanov512d7102018-09-17 19:35:30 -0400311 async def tcp_echo_client(message):
312 reader, writer = await asyncio.open_connection(
313 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200314
Yury Selivanov512d7102018-09-17 19:35:30 -0400315 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200316 writer.write(message.encode())
317
Andrew Svetlov88743422017-12-11 17:35:49 +0200318 data = await reader.read(100)
Yury Selivanov512d7102018-09-17 19:35:30 -0400319 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200320
Yury Selivanov512d7102018-09-17 19:35:30 -0400321 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200322 writer.close()
323
Yury Selivanov512d7102018-09-17 19:35:30 -0400324 asyncio.run(tcp_echo_client('Hello World!'))
325
Victor Stinnered051592014-10-12 20:18:16 +0200326
327.. seealso::
328
Yury Selivanov512d7102018-09-17 19:35:30 -0400329 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
330 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200331
332
333.. _asyncio-tcp-echo-server-streams:
334
335TCP echo server using streams
336-----------------------------
337
338TCP echo server using the :func:`asyncio.start_server` function::
339
340 import asyncio
341
Andrew Svetlov88743422017-12-11 17:35:49 +0200342 async def handle_echo(reader, writer):
343 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200344 message = data.decode()
345 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200346
Yury Selivanov512d7102018-09-17 19:35:30 -0400347 print(f"Received {message!r} from {addr!r}")
348
349 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200350 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200351 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200352
Yury Selivanov512d7102018-09-17 19:35:30 -0400353 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200354 writer.close()
355
Yury Selivanov512d7102018-09-17 19:35:30 -0400356 async def main():
357 server = await asyncio.start_server(
358 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200359
Yury Selivanov512d7102018-09-17 19:35:30 -0400360 addr = server.sockets[0].getsockname()
361 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200362
Yury Selivanov512d7102018-09-17 19:35:30 -0400363 async with server:
364 await server.serve_forever()
365
366 asyncio.run(main())
367
Victor Stinnered051592014-10-12 20:18:16 +0200368
369.. seealso::
370
Yury Selivanov512d7102018-09-17 19:35:30 -0400371 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
372 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200373
374
Victor Stinner5121a9b2014-10-11 15:52:14 +0200375Get HTTP headers
376----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100377
378Simple example querying HTTP headers of the URL passed on the command line::
379
380 import asyncio
381 import urllib.parse
382 import sys
383
Miss Islington (bot)fac49762018-08-07 13:33:31 -0700384 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100385 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200386 if url.scheme == 'https':
Yury Selivanov512d7102018-09-17 19:35:30 -0400387 reader, writer = await asyncio.open_connection(
388 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200389 else:
Yury Selivanov512d7102018-09-17 19:35:30 -0400390 reader, writer = await asyncio.open_connection(
391 url.hostname, 80)
392
393 query = (
394 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
395 f"Host: {url.hostname}\r\n"
396 f"\r\n"
397 )
398
Victor Stinnerc520edc2014-01-23 11:25:48 +0100399 writer.write(query.encode('latin-1'))
400 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200401 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100402 if not line:
403 break
Yury Selivanov512d7102018-09-17 19:35:30 -0400404
Victor Stinnerc520edc2014-01-23 11:25:48 +0100405 line = line.decode('latin1').rstrip()
406 if line:
Yury Selivanov512d7102018-09-17 19:35:30 -0400407 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100408
Victor Stinner5121a9b2014-10-11 15:52:14 +0200409 # Ignore the body, close the socket
410 writer.close()
411
Victor Stinnerc520edc2014-01-23 11:25:48 +0100412 url = sys.argv[1]
Yury Selivanov512d7102018-09-17 19:35:30 -0400413 asyncio.run(print_http_headers(url))
414
Victor Stinnerc520edc2014-01-23 11:25:48 +0100415
416Usage::
417
418 python example.py http://example.com/path/page.html
419
Victor Stinner04e6df32014-10-11 16:16:27 +0200420or with HTTPS::
421
422 python example.py https://example.com/path/page.html
423
Yury Selivanov512d7102018-09-17 19:35:30 -0400424
425.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200426
427Register an open socket to wait for data using streams
428------------------------------------------------------
429
430Coroutine waiting until a socket receives data using the
431:func:`open_connection` function::
432
433 import asyncio
Yury Selivanov512d7102018-09-17 19:35:30 -0400434 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200435
Yury Selivanov512d7102018-09-17 19:35:30 -0400436 async def wait_for_data():
437 # Get a reference to the current event loop because
438 # we want to access low-level APIs.
439 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200440
Yury Selivanov512d7102018-09-17 19:35:30 -0400441 # Create a pair of connected sockets.
442 rsock, wsock = socket.socketpair()
443
444 # Register the open socket to wait for data.
445 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200446
447 # Simulate the reception of data from the network
448 loop.call_soon(wsock.send, 'abc'.encode())
449
450 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200451 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200452
453 # Got data, we are done: close the socket
454 print("Received:", data.decode())
455 writer.close()
456
457 # Close the second socket
458 wsock.close()
459
Yury Selivanov512d7102018-09-17 19:35:30 -0400460 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200461
462.. seealso::
463
464 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov512d7102018-09-17 19:35:30 -0400465 <asyncio_example_create_connection>` example uses a low-level protocol and
466 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200467
468 The :ref:`watch a file descriptor for read events
Yury Selivanov512d7102018-09-17 19:35:30 -0400469 <asyncio_example_watch_fd>` example uses the low-level
470 :meth:`loop.add_reader` method to watch a file descriptor.