blob: ca7daabdadd58eb728b88bfdfc277e0a41dd57d1 [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 Selivanovcba00532015-12-16 21:30:52 -05005+++++++++++++++++++++++++++++
6Streams (coroutine based API)
7+++++++++++++++++++++++++++++
Victor Stinner24f8ebf2014-01-23 11:05:01 +01008
lf627d2c82017-07-25 17:03:51 -06009**Source code:** :source:`Lib/asyncio/streams.py`
10
Victor Stinner24f8ebf2014-01-23 11:05:01 +010011Stream functions
12================
13
Guido van Rossum19ff6972015-10-19 13:18:04 -070014.. note::
15
Ned Deilyf38c93f2016-02-16 13:27:04 +110016 The top-level functions in this module are meant as convenience wrappers
Guido van Rossum19ff6972015-10-19 13:18:04 -070017 only; there's really nothing special there, and if they don't do
18 exactly what you want, feel free to copy their code.
19
20
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070021.. coroutinefunction:: open_connection(host=None, port=None, \*, loop=None, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010022
Guido van Rossumf68afd82016-08-08 09:41:21 -070023 A wrapper for :meth:`~AbstractEventLoop.create_connection()` returning a (reader,
Victor Stinner24f8ebf2014-01-23 11:05:01 +010024 writer) pair.
25
26 The reader returned is a :class:`StreamReader` instance; the writer is
27 a :class:`StreamWriter` instance.
28
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070029 When specified, the *loop* argument determines which event loop to use,
30 and the *limit* argument determines the buffer size limit used by the
31 returned :class:`StreamReader` instance.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010032
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070033 The rest of the arguments are passed directly to
34 :meth:`AbstractEventLoop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010035
Yury Selivanov37f15bc2014-02-20 16:20:44 -050036 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010037
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070038 .. versionadded:: 3.7
39
40 The *ssl_handshake_timeout* parameter.
41
42.. coroutinefunction:: start_server(client_connected_cb, host=None, port=None, \*, loop=None, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010043
Victor Stinner8ebeb032014-07-11 23:47:40 +020044 Start a socket server, with a callback for each client connected. The return
Guido van Rossumf68afd82016-08-08 09:41:21 -070045 value is the same as :meth:`~AbstractEventLoop.create_server()`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010046
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070047 The *client_connected_cb* callback is called whenever a new client
48 connection is established. It receives a reader/writer pair as two
49 arguments, the first is a :class:`StreamReader` instance,
50 and the second is a :class:`StreamWriter` instance.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010051
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070052 *client_connected_cb* accepts a plain callable or a
53 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
54 it will be automatically converted into a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010055
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070056 When specified, the *loop* argument determines which event loop to use,
57 and the *limit* argument determines the buffer size limit used by the
58 :class:`StreamReader` instance passed to *client_connected_cb*.
59
60 The rest of the arguments are passed directly to
61 :meth:`~AbstractEventLoop.create_server()`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010062
Yury Selivanov37f15bc2014-02-20 16:20:44 -050063 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010064
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070065 .. versionadded:: 3.7
66
67 The *ssl_handshake_timeout* and *start_serving* parameters.
68
69.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050070
Guido van Rossumf68afd82016-08-08 09:41:21 -070071 A wrapper for :meth:`~AbstractEventLoop.create_unix_connection()` returning
Yury Selivanovd3f8e302014-02-20 14:10:02 -050072 a (reader, writer) pair.
73
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070074 When specified, the *loop* argument determines which event loop to use,
75 and the *limit* argument determines the buffer size limit used by the
76 returned :class:`StreamReader` instance.
77
78 The rest of the arguments are passed directly to
79 :meth:`~AbstractEventLoop.create_unix_connection()`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050080
Yury Selivanov37f15bc2014-02-20 16:20:44 -050081 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050082
83 Availability: UNIX.
84
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070085 .. versionadded:: 3.7
86
87 The *ssl_handshake_timeout* parameter.
88
89 .. versionchanged:: 3.7
90
91 The *path* parameter can now be a :term:`path-like object`
92
93.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \*, loop=None, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050094
95 Start a UNIX Domain Socket server, with a callback for each client connected.
96
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -070097 The *client_connected_cb* callback is called whenever a new client
98 connection is established. It receives a reader/writer pair as two
99 arguments, the first is a :class:`StreamReader` instance,
100 and the second is a :class:`StreamWriter` instance.
101
102 *client_connected_cb* accepts a plain callable or a
103 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
104 it will be automatically converted into a :class:`Task`.
105
106 When specified, the *loop* argument determines which event loop to use,
107 and the *limit* argument determines the buffer size limit used by the
108 :class:`StreamReader` instance passed to *client_connected_cb*.
109
110 The rest of the arguments are passed directly to
111 :meth:`~AbstractEventLoop.create_unix_server()`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500112
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500113 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500114
115 Availability: UNIX.
116
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700117 .. versionadded:: 3.7
118
119 The *ssl_handshake_timeout* and *start_serving* parameters.
120
121 .. versionchanged:: 3.7
122
123 The *path* parameter can now be a :term:`path-like object`.
124
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100125
126StreamReader
127============
128
Miss Islington (bot)e02ca422018-09-11 11:59:29 -0700129.. class:: StreamReader(limit=_DEFAULT_LIMIT, loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100130
Victor Stinner83704962015-02-25 14:24:15 +0100131 This class is :ref:`not thread safe <asyncio-multithreading>`.
132
Miss Islington (bot)e02ca422018-09-11 11:59:29 -0700133 The *limit* argument's default value is set to _DEFAULT_LIMIT which is 2**16 (64 KiB)
134
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100135 .. method:: exception()
136
137 Get the exception.
138
139 .. method:: feed_eof()
140
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500141 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100142
143 .. method:: feed_data(data)
144
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500145 Feed *data* bytes in the internal buffer. Any operations waiting
146 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100147
148 .. method:: set_exception(exc)
149
150 Set the exception.
151
152 .. method:: set_transport(transport)
153
154 Set the transport.
155
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100156 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100157
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500158 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
159 read until EOF and return all read bytes.
160
161 If the EOF was received and the internal buffer is empty,
162 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100163
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500164 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100166 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100167
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500168 Read one line, where "line" is a sequence of bytes ending with ``\n``.
169
170 If EOF is received, and ``\n`` was not found, the method will
171 return the partial read bytes.
172
173 If the EOF was received and the internal buffer is empty,
174 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100175
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500176 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100177
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100178 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100179
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100180 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
181 the stream is reached before *n* can be read, the
182 :attr:`IncompleteReadError.partial` attribute of the exception contains
183 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100184
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500185 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100186
Berker Peksage5b0bd12016-10-18 00:34:46 +0300187 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400188
189 Read data from the stream until ``separator`` is found.
190
191 On success, the data and separator will be removed from the
192 internal buffer (consumed). Returned data will include the
193 separator at the end.
194
195 Configured stream limit is used to check result. Limit sets the
196 maximal length of data that can be returned, not counting the
197 separator.
198
199 If an EOF occurs and the complete separator is still not found,
200 an :exc:`IncompleteReadError` exception will be
201 raised, and the internal buffer will be reset. The
202 :attr:`IncompleteReadError.partial` attribute may contain the
203 separator partially.
204
205 If the data cannot be read because of over limit, a
206 :exc:`LimitOverrunError` exception will be raised, and the data
207 will be left in the internal buffer, so it can be read again.
208
209 .. versionadded:: 3.5.2
210
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500211 .. method:: at_eof()
212
213 Return ``True`` if the buffer is empty and :meth:`feed_eof` was called.
214
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100215
216StreamWriter
217============
218
219.. class:: StreamWriter(transport, protocol, reader, loop)
220
221 Wraps a Transport.
222
223 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
224 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
225 :meth:`drain` which returns an optional :class:`Future` on which you can
226 wait for flow control. It also adds a transport attribute which references
227 the :class:`Transport` directly.
228
Victor Stinner83704962015-02-25 14:24:15 +0100229 This class is :ref:`not thread safe <asyncio-multithreading>`.
230
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100231 .. attribute:: transport
232
233 Transport.
234
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100235 .. method:: can_write_eof()
236
237 Return :const:`True` if the transport supports :meth:`write_eof`,
238 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
239
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100240 .. method:: close()
241
242 Close the transport: see :meth:`BaseTransport.close`.
243
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200244 .. method:: is_closing()
245
246 Return ``True`` if the writer is closing or is closed.
247
248 .. versionadded:: 3.7
249
250 .. coroutinemethod:: wait_closed()
251
252 Wait until the writer is closed.
253
254 Should be called after :meth:`close` to wait until the underlying
255 connection (and the associated transport/protocol pair) is closed.
256
257 .. versionadded:: 3.7
258
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100259 .. coroutinemethod:: drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100260
Victor Stinnere7182972014-11-28 17:45:41 +0100261 Let the write buffer of the underlying transport a chance to be flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100262
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200263 The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100264
265 w.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200266 await w.drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100267
Victor Stinnere7182972014-11-28 17:45:41 +0100268 When the size of the transport buffer reaches the high-water limit (the
269 protocol is paused), block until the size of the buffer is drained down
270 to the low-water limit and the protocol is resumed. When there is nothing
271 to wait for, the yield-from continues immediately.
272
273 Yielding from :meth:`drain` gives the opportunity for the loop to
274 schedule the write operation and flush the buffer. It should especially
275 be used when a possibly large amount of data is written to the transport,
276 and the coroutine does not yield-from between calls to :meth:`write`.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200277
278 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100279
280 .. method:: get_extra_info(name, default=None)
281
282 Return optional transport information: see
283 :meth:`BaseTransport.get_extra_info`.
284
285 .. method:: write(data)
286
287 Write some *data* bytes to the transport: see
288 :meth:`WriteTransport.write`.
289
290 .. method:: writelines(data)
291
292 Write a list (or any iterable) of data bytes to the transport:
293 see :meth:`WriteTransport.writelines`.
294
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100295 .. method:: write_eof()
296
297 Close the write end of the transport after flushing buffered data:
298 see :meth:`WriteTransport.write_eof`.
299
300
301StreamReaderProtocol
302====================
303
304.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None)
305
306 Trivial helper class to adapt between :class:`Protocol` and
Jesus Ceaded4c492016-04-19 21:50:19 +0200307 :class:`StreamReader`. Subclass of :class:`Protocol`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100308
309 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
310 is an optional function called with (stream_reader, stream_writer) when a
311 connection is made, *loop* is the event loop instance to use.
312
313 (This is a helper class instead of making :class:`StreamReader` itself a
314 :class:`Protocol` subclass, because the :class:`StreamReader` has other
R David Murray87d00662015-09-27 12:36:19 -0400315 potential uses, and to prevent the user of the :class:`StreamReader` from
316 accidentally calling inappropriate methods of the protocol.)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100317
Victor Stinnerc520edc2014-01-23 11:25:48 +0100318
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100319IncompleteReadError
320===================
321
322.. exception:: IncompleteReadError
323
Victor Stinner32970b82014-01-27 12:18:49 +0100324 Incomplete read error, subclass of :exc:`EOFError`.
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100325
326 .. attribute:: expected
327
328 Total number of expected bytes (:class:`int`).
329
330 .. attribute:: partial
331
332 Read bytes string before the end of stream was reached (:class:`bytes`).
333
334
Yury Selivanov950204d2016-05-16 16:23:00 -0400335LimitOverrunError
336=================
337
338.. exception:: LimitOverrunError
339
340 Reached the buffer limit while looking for a separator.
341
342 .. attribute:: consumed
343
344 Total number of to be consumed bytes.
345
346
Victor Stinner5121a9b2014-10-11 15:52:14 +0200347Stream examples
348===============
349
Victor Stinnered051592014-10-12 20:18:16 +0200350.. _asyncio-tcp-echo-client-streams:
351
352TCP echo client using streams
353-----------------------------
354
355TCP echo client using the :func:`asyncio.open_connection` function::
356
357 import asyncio
358
Andrew Svetlov88743422017-12-11 17:35:49 +0200359 async def tcp_echo_client(message, loop):
360 reader, writer = await asyncio.open_connection('127.0.0.1', 8888,
361 loop=loop)
Victor Stinnered051592014-10-12 20:18:16 +0200362
363 print('Send: %r' % message)
364 writer.write(message.encode())
365
Andrew Svetlov88743422017-12-11 17:35:49 +0200366 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200367 print('Received: %r' % data.decode())
368
369 print('Close the socket')
370 writer.close()
371
372 message = 'Hello World!'
373 loop = asyncio.get_event_loop()
374 loop.run_until_complete(tcp_echo_client(message, loop))
375 loop.close()
376
377.. seealso::
378
379 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700380 example uses the :meth:`AbstractEventLoop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200381
382
383.. _asyncio-tcp-echo-server-streams:
384
385TCP echo server using streams
386-----------------------------
387
388TCP echo server using the :func:`asyncio.start_server` function::
389
390 import asyncio
391
Andrew Svetlov88743422017-12-11 17:35:49 +0200392 async def handle_echo(reader, writer):
393 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200394 message = data.decode()
395 addr = writer.get_extra_info('peername')
396 print("Received %r from %r" % (message, addr))
397
398 print("Send: %r" % message)
399 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200400 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200401
402 print("Close the client socket")
403 writer.close()
404
405 loop = asyncio.get_event_loop()
406 coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
407 server = loop.run_until_complete(coro)
408
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300409 # Serve requests until Ctrl+C is pressed
Victor Stinnered051592014-10-12 20:18:16 +0200410 print('Serving on {}'.format(server.sockets[0].getsockname()))
411 try:
412 loop.run_forever()
413 except KeyboardInterrupt:
414 pass
415
416 # Close the server
417 server.close()
418 loop.run_until_complete(server.wait_closed())
419 loop.close()
420
421.. seealso::
422
423 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700424 example uses the :meth:`AbstractEventLoop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200425
426
Victor Stinner5121a9b2014-10-11 15:52:14 +0200427Get HTTP headers
428----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100429
430Simple example querying HTTP headers of the URL passed on the command line::
431
432 import asyncio
433 import urllib.parse
434 import sys
435
Miss Islington (bot)fac49762018-08-07 13:33:31 -0700436 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100437 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200438 if url.scheme == 'https':
439 connect = asyncio.open_connection(url.hostname, 443, ssl=True)
440 else:
441 connect = asyncio.open_connection(url.hostname, 80)
Andrew Svetlov88743422017-12-11 17:35:49 +0200442 reader, writer = await connect
Victor Stinner5121a9b2014-10-11 15:52:14 +0200443 query = ('HEAD {path} HTTP/1.0\r\n'
444 'Host: {hostname}\r\n'
445 '\r\n').format(path=url.path or '/', hostname=url.hostname)
Victor Stinnerc520edc2014-01-23 11:25:48 +0100446 writer.write(query.encode('latin-1'))
447 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200448 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100449 if not line:
450 break
451 line = line.decode('latin1').rstrip()
452 if line:
453 print('HTTP header> %s' % line)
454
Victor Stinner5121a9b2014-10-11 15:52:14 +0200455 # Ignore the body, close the socket
456 writer.close()
457
Victor Stinnerc520edc2014-01-23 11:25:48 +0100458 url = sys.argv[1]
459 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400460 task = asyncio.ensure_future(print_http_headers(url))
Victor Stinnerc520edc2014-01-23 11:25:48 +0100461 loop.run_until_complete(task)
Victor Stinnerf40c6632014-01-28 23:32:40 +0100462 loop.close()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100463
464Usage::
465
466 python example.py http://example.com/path/page.html
467
Victor Stinner04e6df32014-10-11 16:16:27 +0200468or with HTTPS::
469
470 python example.py https://example.com/path/page.html
471
472.. _asyncio-register-socket-streams:
473
474Register an open socket to wait for data using streams
475------------------------------------------------------
476
477Coroutine waiting until a socket receives data using the
478:func:`open_connection` function::
479
480 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +0100481 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200482
Andrew Svetlov88743422017-12-11 17:35:49 +0200483 async def wait_for_data(loop):
Victor Stinner04e6df32014-10-11 16:16:27 +0200484 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200485 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200486
487 # Register the open socket to wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200488 reader, writer = await asyncio.open_connection(sock=rsock, loop=loop)
Victor Stinner04e6df32014-10-11 16:16:27 +0200489
490 # Simulate the reception of data from the network
491 loop.call_soon(wsock.send, 'abc'.encode())
492
493 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200494 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200495
496 # Got data, we are done: close the socket
497 print("Received:", data.decode())
498 writer.close()
499
500 # Close the second socket
501 wsock.close()
502
503 loop = asyncio.get_event_loop()
504 loop.run_until_complete(wait_for_data(loop))
505 loop.close()
506
507.. seealso::
508
509 The :ref:`register an open socket to wait for data using a protocol
510 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700511 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200512
513 The :ref:`watch a file descriptor for read events
514 <asyncio-watch-read-event>` example uses the low-level
Guido van Rossumf68afd82016-08-08 09:41:21 -0700515 :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a
Victor Stinner04e6df32014-10-11 16:16:27 +0200516 socket.