blob: 27b5205f1c5b6da0c0bbc868ce93ee548ca83517 [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
Bramb4ec3622018-09-11 20:45:26 +0200149.. class:: StreamReader(limit=_DEFAULT_LIMIT, 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
Bramb4ec3622018-09-11 20:45:26 +0200153 The *limit* argument's default value is set to _DEFAULT_LIMIT which is 2**16 (64 KiB)
154
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100155 .. method:: exception()
156
157 Get the exception.
158
159 .. method:: feed_eof()
160
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500161 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100162
163 .. method:: feed_data(data)
164
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500165 Feed *data* bytes in the internal buffer. Any operations waiting
166 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100167
168 .. method:: set_exception(exc)
169
170 Set the exception.
171
172 .. method:: set_transport(transport)
173
174 Set the transport.
175
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100176 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100177
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500178 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
179 read until EOF and return all read bytes.
180
181 If the EOF was received and the internal buffer is empty,
182 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100183
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100184 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100185
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500186 Read one line, where "line" is a sequence of bytes ending with ``\n``.
187
188 If EOF is received, and ``\n`` was not found, the method will
189 return the partial read bytes.
190
191 If the EOF was received and the internal buffer is empty,
192 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100193
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100194 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100195
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100196 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
197 the stream is reached before *n* can be read, the
198 :attr:`IncompleteReadError.partial` attribute of the exception contains
199 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100200
Berker Peksage5b0bd12016-10-18 00:34:46 +0300201 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400202
203 Read data from the stream until ``separator`` is found.
204
205 On success, the data and separator will be removed from the
206 internal buffer (consumed). Returned data will include the
207 separator at the end.
208
209 Configured stream limit is used to check result. Limit sets the
210 maximal length of data that can be returned, not counting the
211 separator.
212
213 If an EOF occurs and the complete separator is still not found,
214 an :exc:`IncompleteReadError` exception will be
215 raised, and the internal buffer will be reset. The
216 :attr:`IncompleteReadError.partial` attribute may contain the
217 separator partially.
218
219 If the data cannot be read because of over limit, a
220 :exc:`LimitOverrunError` exception will be raised, and the data
221 will be left in the internal buffer, so it can be read again.
222
223 .. versionadded:: 3.5.2
224
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500225 .. method:: at_eof()
226
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700227 Return ``True`` if the buffer is empty and :meth:`feed_eof`
228 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500229
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100230
231StreamWriter
232============
233
234.. class:: StreamWriter(transport, protocol, reader, loop)
235
236 Wraps a Transport.
237
238 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
239 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
240 :meth:`drain` which returns an optional :class:`Future` on which you can
241 wait for flow control. It also adds a transport attribute which references
242 the :class:`Transport` directly.
243
Victor Stinner83704962015-02-25 14:24:15 +0100244 This class is :ref:`not thread safe <asyncio-multithreading>`.
245
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100246 .. attribute:: transport
247
248 Transport.
249
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100250 .. method:: can_write_eof()
251
252 Return :const:`True` if the transport supports :meth:`write_eof`,
253 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
254
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100255 .. method:: close()
256
257 Close the transport: see :meth:`BaseTransport.close`.
258
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200259 .. method:: is_closing()
260
261 Return ``True`` if the writer is closing or is closed.
262
263 .. versionadded:: 3.7
264
265 .. coroutinemethod:: wait_closed()
266
267 Wait until the writer is closed.
268
269 Should be called after :meth:`close` to wait until the underlying
270 connection (and the associated transport/protocol pair) is closed.
271
272 .. versionadded:: 3.7
273
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100274 .. coroutinemethod:: drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100275
Victor Stinnere7182972014-11-28 17:45:41 +0100276 Let the write buffer of the underlying transport a chance to be flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100277
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200278 The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100279
280 w.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200281 await w.drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100282
Victor Stinnere7182972014-11-28 17:45:41 +0100283 When the size of the transport buffer reaches the high-water limit (the
284 protocol is paused), block until the size of the buffer is drained down
285 to the low-water limit and the protocol is resumed. When there is nothing
286 to wait for, the yield-from continues immediately.
287
288 Yielding from :meth:`drain` gives the opportunity for the loop to
289 schedule the write operation and flush the buffer. It should especially
290 be used when a possibly large amount of data is written to the transport,
291 and the coroutine does not yield-from between calls to :meth:`write`.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200292
293 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100294
295 .. method:: get_extra_info(name, default=None)
296
297 Return optional transport information: see
298 :meth:`BaseTransport.get_extra_info`.
299
300 .. method:: write(data)
301
302 Write some *data* bytes to the transport: see
303 :meth:`WriteTransport.write`.
304
305 .. method:: writelines(data)
306
307 Write a list (or any iterable) of data bytes to the transport:
308 see :meth:`WriteTransport.writelines`.
309
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100310 .. method:: write_eof()
311
312 Close the write end of the transport after flushing buffered data:
313 see :meth:`WriteTransport.write_eof`.
314
315
316StreamReaderProtocol
317====================
318
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700319.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, \
320 loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100321
322 Trivial helper class to adapt between :class:`Protocol` and
Jesus Ceaded4c492016-04-19 21:50:19 +0200323 :class:`StreamReader`. Subclass of :class:`Protocol`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100324
325 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
326 is an optional function called with (stream_reader, stream_writer) when a
327 connection is made, *loop* is the event loop instance to use.
328
329 (This is a helper class instead of making :class:`StreamReader` itself a
330 :class:`Protocol` subclass, because the :class:`StreamReader` has other
R David Murray87d00662015-09-27 12:36:19 -0400331 potential uses, and to prevent the user of the :class:`StreamReader` from
332 accidentally calling inappropriate methods of the protocol.)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100333
Victor Stinnerc520edc2014-01-23 11:25:48 +0100334
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700335Examples
336========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200337
Victor Stinnered051592014-10-12 20:18:16 +0200338.. _asyncio-tcp-echo-client-streams:
339
340TCP echo client using streams
341-----------------------------
342
343TCP echo client using the :func:`asyncio.open_connection` function::
344
345 import asyncio
346
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700347 async def tcp_echo_client(message):
348 reader, writer = await asyncio.open_connection(
349 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200350
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700351 print(f'Send: {message!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200352 writer.write(message.encode())
353
Andrew Svetlov88743422017-12-11 17:35:49 +0200354 data = await reader.read(100)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700355 print(f'Received: {data.decode()!r}')
Victor Stinnered051592014-10-12 20:18:16 +0200356
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700357 print('Close the connection')
Victor Stinnered051592014-10-12 20:18:16 +0200358 writer.close()
359
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700360 asyncio.run(tcp_echo_client('Hello World!'))
361
Victor Stinnered051592014-10-12 20:18:16 +0200362
363.. seealso::
364
365 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700366 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200367
368
369.. _asyncio-tcp-echo-server-streams:
370
371TCP echo server using streams
372-----------------------------
373
374TCP echo server using the :func:`asyncio.start_server` function::
375
376 import asyncio
377
Andrew Svetlov88743422017-12-11 17:35:49 +0200378 async def handle_echo(reader, writer):
379 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200380 message = data.decode()
381 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200382
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700383 print(f"Received {message!r} from {addr!r}")
384
385 print(f"Send: {message!r}")
Victor Stinnered051592014-10-12 20:18:16 +0200386 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200387 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200388
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700389 print("Close the connection")
Victor Stinnered051592014-10-12 20:18:16 +0200390 writer.close()
391
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700392 async def main():
393 server = await asyncio.start_server(
394 handle_echo, '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200395
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700396 addr = server.sockets[0].getsockname()
397 print(f'Serving on {addr}')
Victor Stinnered051592014-10-12 20:18:16 +0200398
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700399 async with server:
400 await server.serve_forever()
401
402 asyncio.run(main())
403
Victor Stinnered051592014-10-12 20:18:16 +0200404
405.. seealso::
406
407 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700408 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200409
410
Victor Stinner5121a9b2014-10-11 15:52:14 +0200411Get HTTP headers
412----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100413
414Simple example querying HTTP headers of the URL passed on the command line::
415
416 import asyncio
417 import urllib.parse
418 import sys
419
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400420 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100421 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200422 if url.scheme == 'https':
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700423 reader, writer = await asyncio.open_connection(
424 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200425 else:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700426 reader, writer = await asyncio.open_connection(
427 url.hostname, 80)
428
429 query = (
430 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
431 f"Host: {url.hostname}\r\n"
432 f"\r\n"
433 )
434
Victor Stinnerc520edc2014-01-23 11:25:48 +0100435 writer.write(query.encode('latin-1'))
436 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200437 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100438 if not line:
439 break
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700440
Victor Stinnerc520edc2014-01-23 11:25:48 +0100441 line = line.decode('latin1').rstrip()
442 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700443 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100444
Victor Stinner5121a9b2014-10-11 15:52:14 +0200445 # Ignore the body, close the socket
446 writer.close()
447
Victor Stinnerc520edc2014-01-23 11:25:48 +0100448 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700449 asyncio.run(print_http_headers(url))
450
Victor Stinnerc520edc2014-01-23 11:25:48 +0100451
452Usage::
453
454 python example.py http://example.com/path/page.html
455
Victor Stinner04e6df32014-10-11 16:16:27 +0200456or with HTTPS::
457
458 python example.py https://example.com/path/page.html
459
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700460
Victor Stinner04e6df32014-10-11 16:16:27 +0200461.. _asyncio-register-socket-streams:
462
463Register an open socket to wait for data using streams
464------------------------------------------------------
465
466Coroutine waiting until a socket receives data using the
467:func:`open_connection` function::
468
469 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700470 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200471
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700472 async def wait_for_data():
473 # Get a reference to the current event loop because
474 # we want to access low-level APIs.
475 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200476
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700477 # Create a pair of connected sockets.
478 rsock, wsock = socket.socketpair()
479
480 # Register the open socket to wait for data.
481 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200482
483 # Simulate the reception of data from the network
484 loop.call_soon(wsock.send, 'abc'.encode())
485
486 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200487 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200488
489 # Got data, we are done: close the socket
490 print("Received:", data.decode())
491 writer.close()
492
493 # Close the second socket
494 wsock.close()
495
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700496 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200497
498.. seealso::
499
500 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700501 <asyncio-register-socket>` example uses a low-level protocol and
502 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200503
504 The :ref:`watch a file descriptor for read events
505 <asyncio-watch-read-event>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700506 :meth:`loop.add_reader` method to watch a file descriptor.