blob: f662e72233372550d0da39849e62bc392654d87c [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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040021.. 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040029 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040033 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040038 .. 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040047 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040052 *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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040056 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040065 .. 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040074 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040085 .. 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040097 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
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400117 .. 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
Victor Stinner08444382014-02-02 22:43:39 +0100129.. class:: StreamReader(limit=None, 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
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100133 .. method:: exception()
134
135 Get the exception.
136
137 .. method:: feed_eof()
138
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500139 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100140
141 .. method:: feed_data(data)
142
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500143 Feed *data* bytes in the internal buffer. Any operations waiting
144 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100145
146 .. method:: set_exception(exc)
147
148 Set the exception.
149
150 .. method:: set_transport(transport)
151
152 Set the transport.
153
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100154 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100155
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500156 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
157 read until EOF and return all read bytes.
158
159 If the EOF was received and the internal buffer is empty,
160 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100161
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500162 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100163
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100164 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500166 Read one line, where "line" is a sequence of bytes ending with ``\n``.
167
168 If EOF is received, and ``\n`` was not found, the method will
169 return the partial read bytes.
170
171 If the EOF was received and the internal buffer is empty,
172 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100173
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500174 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100175
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100176 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100177
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100178 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
179 the stream is reached before *n* can be read, the
180 :attr:`IncompleteReadError.partial` attribute of the exception contains
181 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100182
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500183 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100184
Berker Peksage5b0bd12016-10-18 00:34:46 +0300185 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400186
187 Read data from the stream until ``separator`` is found.
188
189 On success, the data and separator will be removed from the
190 internal buffer (consumed). Returned data will include the
191 separator at the end.
192
193 Configured stream limit is used to check result. Limit sets the
194 maximal length of data that can be returned, not counting the
195 separator.
196
197 If an EOF occurs and the complete separator is still not found,
198 an :exc:`IncompleteReadError` exception will be
199 raised, and the internal buffer will be reset. The
200 :attr:`IncompleteReadError.partial` attribute may contain the
201 separator partially.
202
203 If the data cannot be read because of over limit, a
204 :exc:`LimitOverrunError` exception will be raised, and the data
205 will be left in the internal buffer, so it can be read again.
206
207 .. versionadded:: 3.5.2
208
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500209 .. method:: at_eof()
210
211 Return ``True`` if the buffer is empty and :meth:`feed_eof` was called.
212
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100213
214StreamWriter
215============
216
217.. class:: StreamWriter(transport, protocol, reader, loop)
218
219 Wraps a Transport.
220
221 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
222 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
223 :meth:`drain` which returns an optional :class:`Future` on which you can
224 wait for flow control. It also adds a transport attribute which references
225 the :class:`Transport` directly.
226
Victor Stinner83704962015-02-25 14:24:15 +0100227 This class is :ref:`not thread safe <asyncio-multithreading>`.
228
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100229 .. attribute:: transport
230
231 Transport.
232
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100233 .. method:: can_write_eof()
234
235 Return :const:`True` if the transport supports :meth:`write_eof`,
236 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
237
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100238 .. method:: close()
239
240 Close the transport: see :meth:`BaseTransport.close`.
241
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200242 .. method:: is_closing()
243
244 Return ``True`` if the writer is closing or is closed.
245
246 .. versionadded:: 3.7
247
248 .. coroutinemethod:: wait_closed()
249
250 Wait until the writer is closed.
251
252 Should be called after :meth:`close` to wait until the underlying
253 connection (and the associated transport/protocol pair) is closed.
254
255 .. versionadded:: 3.7
256
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100257 .. coroutinemethod:: drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100258
Victor Stinnere7182972014-11-28 17:45:41 +0100259 Let the write buffer of the underlying transport a chance to be flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100260
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200261 The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100262
263 w.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200264 await w.drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100265
Victor Stinnere7182972014-11-28 17:45:41 +0100266 When the size of the transport buffer reaches the high-water limit (the
267 protocol is paused), block until the size of the buffer is drained down
268 to the low-water limit and the protocol is resumed. When there is nothing
269 to wait for, the yield-from continues immediately.
270
271 Yielding from :meth:`drain` gives the opportunity for the loop to
272 schedule the write operation and flush the buffer. It should especially
273 be used when a possibly large amount of data is written to the transport,
274 and the coroutine does not yield-from between calls to :meth:`write`.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200275
276 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100277
278 .. method:: get_extra_info(name, default=None)
279
280 Return optional transport information: see
281 :meth:`BaseTransport.get_extra_info`.
282
283 .. method:: write(data)
284
285 Write some *data* bytes to the transport: see
286 :meth:`WriteTransport.write`.
287
288 .. method:: writelines(data)
289
290 Write a list (or any iterable) of data bytes to the transport:
291 see :meth:`WriteTransport.writelines`.
292
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100293 .. method:: write_eof()
294
295 Close the write end of the transport after flushing buffered data:
296 see :meth:`WriteTransport.write_eof`.
297
298
299StreamReaderProtocol
300====================
301
302.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None)
303
304 Trivial helper class to adapt between :class:`Protocol` and
Jesus Ceaded4c492016-04-19 21:50:19 +0200305 :class:`StreamReader`. Subclass of :class:`Protocol`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100306
307 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
308 is an optional function called with (stream_reader, stream_writer) when a
309 connection is made, *loop* is the event loop instance to use.
310
311 (This is a helper class instead of making :class:`StreamReader` itself a
312 :class:`Protocol` subclass, because the :class:`StreamReader` has other
R David Murray87d00662015-09-27 12:36:19 -0400313 potential uses, and to prevent the user of the :class:`StreamReader` from
314 accidentally calling inappropriate methods of the protocol.)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100315
Victor Stinnerc520edc2014-01-23 11:25:48 +0100316
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100317IncompleteReadError
318===================
319
320.. exception:: IncompleteReadError
321
Victor Stinner32970b82014-01-27 12:18:49 +0100322 Incomplete read error, subclass of :exc:`EOFError`.
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100323
324 .. attribute:: expected
325
326 Total number of expected bytes (:class:`int`).
327
328 .. attribute:: partial
329
330 Read bytes string before the end of stream was reached (:class:`bytes`).
331
332
Yury Selivanov950204d2016-05-16 16:23:00 -0400333LimitOverrunError
334=================
335
336.. exception:: LimitOverrunError
337
338 Reached the buffer limit while looking for a separator.
339
340 .. attribute:: consumed
341
342 Total number of to be consumed bytes.
343
344
Victor Stinner5121a9b2014-10-11 15:52:14 +0200345Stream examples
346===============
347
Victor Stinnered051592014-10-12 20:18:16 +0200348.. _asyncio-tcp-echo-client-streams:
349
350TCP echo client using streams
351-----------------------------
352
353TCP echo client using the :func:`asyncio.open_connection` function::
354
355 import asyncio
356
Andrew Svetlov88743422017-12-11 17:35:49 +0200357 async def tcp_echo_client(message, loop):
358 reader, writer = await asyncio.open_connection('127.0.0.1', 8888,
359 loop=loop)
Victor Stinnered051592014-10-12 20:18:16 +0200360
361 print('Send: %r' % message)
362 writer.write(message.encode())
363
Andrew Svetlov88743422017-12-11 17:35:49 +0200364 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200365 print('Received: %r' % data.decode())
366
367 print('Close the socket')
368 writer.close()
369
370 message = 'Hello World!'
371 loop = asyncio.get_event_loop()
372 loop.run_until_complete(tcp_echo_client(message, loop))
373 loop.close()
374
375.. seealso::
376
377 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700378 example uses the :meth:`AbstractEventLoop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200379
380
381.. _asyncio-tcp-echo-server-streams:
382
383TCP echo server using streams
384-----------------------------
385
386TCP echo server using the :func:`asyncio.start_server` function::
387
388 import asyncio
389
Andrew Svetlov88743422017-12-11 17:35:49 +0200390 async def handle_echo(reader, writer):
391 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200392 message = data.decode()
393 addr = writer.get_extra_info('peername')
394 print("Received %r from %r" % (message, addr))
395
396 print("Send: %r" % message)
397 writer.write(data)
Andrew Svetlov88743422017-12-11 17:35:49 +0200398 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200399
400 print("Close the client socket")
401 writer.close()
402
403 loop = asyncio.get_event_loop()
404 coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
405 server = loop.run_until_complete(coro)
406
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300407 # Serve requests until Ctrl+C is pressed
Victor Stinnered051592014-10-12 20:18:16 +0200408 print('Serving on {}'.format(server.sockets[0].getsockname()))
409 try:
410 loop.run_forever()
411 except KeyboardInterrupt:
412 pass
413
414 # Close the server
415 server.close()
416 loop.run_until_complete(server.wait_closed())
417 loop.close()
418
419.. seealso::
420
421 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700422 example uses the :meth:`AbstractEventLoop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200423
424
Victor Stinner5121a9b2014-10-11 15:52:14 +0200425Get HTTP headers
426----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100427
428Simple example querying HTTP headers of the URL passed on the command line::
429
430 import asyncio
431 import urllib.parse
432 import sys
433
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400434 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100435 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200436 if url.scheme == 'https':
437 connect = asyncio.open_connection(url.hostname, 443, ssl=True)
438 else:
439 connect = asyncio.open_connection(url.hostname, 80)
Andrew Svetlov88743422017-12-11 17:35:49 +0200440 reader, writer = await connect
Victor Stinner5121a9b2014-10-11 15:52:14 +0200441 query = ('HEAD {path} HTTP/1.0\r\n'
442 'Host: {hostname}\r\n'
443 '\r\n').format(path=url.path or '/', hostname=url.hostname)
Victor Stinnerc520edc2014-01-23 11:25:48 +0100444 writer.write(query.encode('latin-1'))
445 while True:
Andrew Svetlov88743422017-12-11 17:35:49 +0200446 line = await reader.readline()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100447 if not line:
448 break
449 line = line.decode('latin1').rstrip()
450 if line:
451 print('HTTP header> %s' % line)
452
Victor Stinner5121a9b2014-10-11 15:52:14 +0200453 # Ignore the body, close the socket
454 writer.close()
455
Victor Stinnerc520edc2014-01-23 11:25:48 +0100456 url = sys.argv[1]
457 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400458 task = asyncio.ensure_future(print_http_headers(url))
Victor Stinnerc520edc2014-01-23 11:25:48 +0100459 loop.run_until_complete(task)
Victor Stinnerf40c6632014-01-28 23:32:40 +0100460 loop.close()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100461
462Usage::
463
464 python example.py http://example.com/path/page.html
465
Victor Stinner04e6df32014-10-11 16:16:27 +0200466or with HTTPS::
467
468 python example.py https://example.com/path/page.html
469
470.. _asyncio-register-socket-streams:
471
472Register an open socket to wait for data using streams
473------------------------------------------------------
474
475Coroutine waiting until a socket receives data using the
476:func:`open_connection` function::
477
478 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +0100479 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200480
Andrew Svetlov88743422017-12-11 17:35:49 +0200481 async def wait_for_data(loop):
Victor Stinner04e6df32014-10-11 16:16:27 +0200482 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200483 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200484
485 # Register the open socket to wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200486 reader, writer = await asyncio.open_connection(sock=rsock, loop=loop)
Victor Stinner04e6df32014-10-11 16:16:27 +0200487
488 # Simulate the reception of data from the network
489 loop.call_soon(wsock.send, 'abc'.encode())
490
491 # Wait for data
Andrew Svetlov88743422017-12-11 17:35:49 +0200492 data = await reader.read(100)
Victor Stinner04e6df32014-10-11 16:16:27 +0200493
494 # Got data, we are done: close the socket
495 print("Received:", data.decode())
496 writer.close()
497
498 # Close the second socket
499 wsock.close()
500
501 loop = asyncio.get_event_loop()
502 loop.run_until_complete(wait_for_data(loop))
503 loop.close()
504
505.. seealso::
506
507 The :ref:`register an open socket to wait for data using a protocol
508 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700509 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200510
511 The :ref:`watch a file descriptor for read events
512 <asyncio-watch-read-event>` example uses the low-level
Guido van Rossumf68afd82016-08-08 09:41:21 -0700513 :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a
Victor Stinner04e6df32014-10-11 16:16:27 +0200514 socket.