blob: fa076df84a3d2499670c19893f0c5159474c4e86 [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
9Stream functions
10================
11
Guido van Rossum19ff6972015-10-19 13:18:04 -070012.. note::
13
Ned Deilyf38c93f2016-02-16 13:27:04 +110014 The top-level functions in this module are meant as convenience wrappers
Guido van Rossum19ff6972015-10-19 13:18:04 -070015 only; there's really nothing special there, and if they don't do
16 exactly what you want, feel free to copy their code.
17
18
Victor Stinnerbdd574d2015-02-12 22:49:18 +010019.. coroutinefunction:: open_connection(host=None, port=None, \*, loop=None, limit=None, \*\*kwds)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010020
21 A wrapper for :meth:`~BaseEventLoop.create_connection()` returning a (reader,
22 writer) pair.
23
24 The reader returned is a :class:`StreamReader` instance; the writer is
25 a :class:`StreamWriter` instance.
26
27 The arguments are all the usual arguments to
28 :meth:`BaseEventLoop.create_connection` except *protocol_factory*; most
29 common are positional host and port, with various optional keyword arguments
30 following.
31
32 Additional optional keyword arguments are *loop* (to set the event loop
33 instance to use) and *limit* (to set the buffer limit passed to the
34 :class:`StreamReader`).
35
Yury Selivanov37f15bc2014-02-20 16:20:44 -050036 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010037
Victor Stinnerbdd574d2015-02-12 22:49:18 +010038.. coroutinefunction:: start_server(client_connected_cb, host=None, port=None, \*, loop=None, limit=None, \*\*kwds)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010039
Victor Stinner8ebeb032014-07-11 23:47:40 +020040 Start a socket server, with a callback for each client connected. The return
41 value is the same as :meth:`~BaseEventLoop.create_server()`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010042
Victor Stinner8ebeb032014-07-11 23:47:40 +020043 The *client_connected_cb* parameter is called with two parameters:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010044 *client_reader*, *client_writer*. *client_reader* is a
45 :class:`StreamReader` object, while *client_writer* is a
Victor Stinner8ebeb032014-07-11 23:47:40 +020046 :class:`StreamWriter` object. The *client_connected_cb* parameter can
47 either be a plain callback function or a :ref:`coroutine function
48 <coroutine>`; if it is a coroutine function, it will be automatically
Victor Stinner337e03f2014-08-11 01:11:13 +020049 converted into a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010050
51 The rest of the arguments are all the usual arguments to
52 :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most
Victor Stinner8ebeb032014-07-11 23:47:40 +020053 common are positional *host* and *port*, with various optional keyword
54 arguments following.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010055
56 Additional optional keyword arguments are *loop* (to set the event loop
57 instance to use) and *limit* (to set the buffer limit passed to the
58 :class:`StreamReader`).
59
Yury Selivanov37f15bc2014-02-20 16:20:44 -050060 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010061
Victor Stinnerbdd574d2015-02-12 22:49:18 +010062.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, limit=None, **kwds)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050063
64 A wrapper for :meth:`~BaseEventLoop.create_unix_connection()` returning
65 a (reader, writer) pair.
66
67 See :func:`open_connection` for information about return value and other
68 details.
69
Yury Selivanov37f15bc2014-02-20 16:20:44 -050070 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050071
72 Availability: UNIX.
73
Victor Stinnerbdd574d2015-02-12 22:49:18 +010074.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \*, loop=None, limit=None, **kwds)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050075
76 Start a UNIX Domain Socket server, with a callback for each client connected.
77
78 See :func:`start_server` for information about return value and other
79 details.
80
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
Victor Stinner24f8ebf2014-01-23 11:05:01 +010085
86StreamReader
87============
88
Victor Stinner08444382014-02-02 22:43:39 +010089.. class:: StreamReader(limit=None, loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010090
Victor Stinner83704962015-02-25 14:24:15 +010091 This class is :ref:`not thread safe <asyncio-multithreading>`.
92
Victor Stinner24f8ebf2014-01-23 11:05:01 +010093 .. method:: exception()
94
95 Get the exception.
96
97 .. method:: feed_eof()
98
Yury Selivanovd3f8e302014-02-20 14:10:02 -050099 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100100
101 .. method:: feed_data(data)
102
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500103 Feed *data* bytes in the internal buffer. Any operations waiting
104 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100105
106 .. method:: set_exception(exc)
107
108 Set the exception.
109
110 .. method:: set_transport(transport)
111
112 Set the transport.
113
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100114 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100115
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500116 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
117 read until EOF and return all read bytes.
118
119 If the EOF was received and the internal buffer is empty,
120 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100121
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500122 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100123
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100124 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100125
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500126 Read one line, where "line" is a sequence of bytes ending with ``\n``.
127
128 If EOF is received, and ``\n`` was not found, the method will
129 return the partial read bytes.
130
131 If the EOF was received and the internal buffer is empty,
132 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100133
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500134 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100135
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100136 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100137
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100138 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
139 the stream is reached before *n* can be read, the
140 :attr:`IncompleteReadError.partial` attribute of the exception contains
141 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100142
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500143 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100144
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500145 .. method:: at_eof()
146
147 Return ``True`` if the buffer is empty and :meth:`feed_eof` was called.
148
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100149
150StreamWriter
151============
152
153.. class:: StreamWriter(transport, protocol, reader, loop)
154
155 Wraps a Transport.
156
157 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
158 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
159 :meth:`drain` which returns an optional :class:`Future` on which you can
160 wait for flow control. It also adds a transport attribute which references
161 the :class:`Transport` directly.
162
Victor Stinner83704962015-02-25 14:24:15 +0100163 This class is :ref:`not thread safe <asyncio-multithreading>`.
164
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165 .. attribute:: transport
166
167 Transport.
168
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100169 .. method:: can_write_eof()
170
171 Return :const:`True` if the transport supports :meth:`write_eof`,
172 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
173
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100174 .. method:: close()
175
176 Close the transport: see :meth:`BaseTransport.close`.
177
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100178 .. coroutinemethod:: drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100179
Victor Stinnere7182972014-11-28 17:45:41 +0100180 Let the write buffer of the underlying transport a chance to be flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100181
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200182 The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100183
184 w.write(data)
185 yield from w.drain()
186
Victor Stinnere7182972014-11-28 17:45:41 +0100187 When the size of the transport buffer reaches the high-water limit (the
188 protocol is paused), block until the size of the buffer is drained down
189 to the low-water limit and the protocol is resumed. When there is nothing
190 to wait for, the yield-from continues immediately.
191
192 Yielding from :meth:`drain` gives the opportunity for the loop to
193 schedule the write operation and flush the buffer. It should especially
194 be used when a possibly large amount of data is written to the transport,
195 and the coroutine does not yield-from between calls to :meth:`write`.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200196
197 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100198
199 .. method:: get_extra_info(name, default=None)
200
201 Return optional transport information: see
202 :meth:`BaseTransport.get_extra_info`.
203
204 .. method:: write(data)
205
206 Write some *data* bytes to the transport: see
207 :meth:`WriteTransport.write`.
208
209 .. method:: writelines(data)
210
211 Write a list (or any iterable) of data bytes to the transport:
212 see :meth:`WriteTransport.writelines`.
213
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100214 .. method:: write_eof()
215
216 Close the write end of the transport after flushing buffered data:
217 see :meth:`WriteTransport.write_eof`.
218
219
220StreamReaderProtocol
221====================
222
223.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None)
224
225 Trivial helper class to adapt between :class:`Protocol` and
Jesus Ceaded4c492016-04-19 21:50:19 +0200226 :class:`StreamReader`. Subclass of :class:`Protocol`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100227
228 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
229 is an optional function called with (stream_reader, stream_writer) when a
230 connection is made, *loop* is the event loop instance to use.
231
232 (This is a helper class instead of making :class:`StreamReader` itself a
233 :class:`Protocol` subclass, because the :class:`StreamReader` has other
R David Murray87d00662015-09-27 12:36:19 -0400234 potential uses, and to prevent the user of the :class:`StreamReader` from
235 accidentally calling inappropriate methods of the protocol.)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100236
Victor Stinnerc520edc2014-01-23 11:25:48 +0100237
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100238IncompleteReadError
239===================
240
241.. exception:: IncompleteReadError
242
Victor Stinner32970b82014-01-27 12:18:49 +0100243 Incomplete read error, subclass of :exc:`EOFError`.
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100244
245 .. attribute:: expected
246
247 Total number of expected bytes (:class:`int`).
248
249 .. attribute:: partial
250
251 Read bytes string before the end of stream was reached (:class:`bytes`).
252
253
Victor Stinner5121a9b2014-10-11 15:52:14 +0200254Stream examples
255===============
256
Victor Stinnered051592014-10-12 20:18:16 +0200257.. _asyncio-tcp-echo-client-streams:
258
259TCP echo client using streams
260-----------------------------
261
262TCP echo client using the :func:`asyncio.open_connection` function::
263
264 import asyncio
265
Victor Stinnered8e3a92014-10-13 00:55:50 +0200266 @asyncio.coroutine
Victor Stinnered051592014-10-12 20:18:16 +0200267 def tcp_echo_client(message, loop):
268 reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888,
269 loop=loop)
270
271 print('Send: %r' % message)
272 writer.write(message.encode())
273
274 data = yield from reader.read(100)
275 print('Received: %r' % data.decode())
276
277 print('Close the socket')
278 writer.close()
279
280 message = 'Hello World!'
281 loop = asyncio.get_event_loop()
282 loop.run_until_complete(tcp_echo_client(message, loop))
283 loop.close()
284
285.. seealso::
286
287 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
288 example uses the :meth:`BaseEventLoop.create_connection` method.
289
290
291.. _asyncio-tcp-echo-server-streams:
292
293TCP echo server using streams
294-----------------------------
295
296TCP echo server using the :func:`asyncio.start_server` function::
297
298 import asyncio
299
300 @asyncio.coroutine
301 def handle_echo(reader, writer):
302 data = yield from reader.read(100)
303 message = data.decode()
304 addr = writer.get_extra_info('peername')
305 print("Received %r from %r" % (message, addr))
306
307 print("Send: %r" % message)
308 writer.write(data)
309 yield from writer.drain()
310
311 print("Close the client socket")
312 writer.close()
313
314 loop = asyncio.get_event_loop()
315 coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
316 server = loop.run_until_complete(coro)
317
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300318 # Serve requests until Ctrl+C is pressed
Victor Stinnered051592014-10-12 20:18:16 +0200319 print('Serving on {}'.format(server.sockets[0].getsockname()))
320 try:
321 loop.run_forever()
322 except KeyboardInterrupt:
323 pass
324
325 # Close the server
326 server.close()
327 loop.run_until_complete(server.wait_closed())
328 loop.close()
329
330.. seealso::
331
332 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
333 example uses the :meth:`BaseEventLoop.create_server` method.
334
335
Victor Stinner5121a9b2014-10-11 15:52:14 +0200336Get HTTP headers
337----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100338
339Simple example querying HTTP headers of the URL passed on the command line::
340
341 import asyncio
342 import urllib.parse
343 import sys
344
345 @asyncio.coroutine
346 def print_http_headers(url):
347 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200348 if url.scheme == 'https':
349 connect = asyncio.open_connection(url.hostname, 443, ssl=True)
350 else:
351 connect = asyncio.open_connection(url.hostname, 80)
352 reader, writer = yield from connect
353 query = ('HEAD {path} HTTP/1.0\r\n'
354 'Host: {hostname}\r\n'
355 '\r\n').format(path=url.path or '/', hostname=url.hostname)
Victor Stinnerc520edc2014-01-23 11:25:48 +0100356 writer.write(query.encode('latin-1'))
357 while True:
358 line = yield from reader.readline()
359 if not line:
360 break
361 line = line.decode('latin1').rstrip()
362 if line:
363 print('HTTP header> %s' % line)
364
Victor Stinner5121a9b2014-10-11 15:52:14 +0200365 # Ignore the body, close the socket
366 writer.close()
367
Victor Stinnerc520edc2014-01-23 11:25:48 +0100368 url = sys.argv[1]
369 loop = asyncio.get_event_loop()
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400370 task = asyncio.ensure_future(print_http_headers(url))
Victor Stinnerc520edc2014-01-23 11:25:48 +0100371 loop.run_until_complete(task)
Victor Stinnerf40c6632014-01-28 23:32:40 +0100372 loop.close()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100373
374Usage::
375
376 python example.py http://example.com/path/page.html
377
Victor Stinner04e6df32014-10-11 16:16:27 +0200378or with HTTPS::
379
380 python example.py https://example.com/path/page.html
381
382.. _asyncio-register-socket-streams:
383
384Register an open socket to wait for data using streams
385------------------------------------------------------
386
387Coroutine waiting until a socket receives data using the
388:func:`open_connection` function::
389
390 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200391 try:
392 from socket import socketpair
393 except ImportError:
394 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200395
Victor Stinnered8e3a92014-10-13 00:55:50 +0200396 @asyncio.coroutine
Victor Stinner04e6df32014-10-11 16:16:27 +0200397 def wait_for_data(loop):
398 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200399 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200400
401 # Register the open socket to wait for data
402 reader, writer = yield from asyncio.open_connection(sock=rsock, loop=loop)
403
404 # Simulate the reception of data from the network
405 loop.call_soon(wsock.send, 'abc'.encode())
406
407 # Wait for data
408 data = yield from reader.read(100)
409
410 # Got data, we are done: close the socket
411 print("Received:", data.decode())
412 writer.close()
413
414 # Close the second socket
415 wsock.close()
416
417 loop = asyncio.get_event_loop()
418 loop.run_until_complete(wait_for_data(loop))
419 loop.close()
420
421.. seealso::
422
423 The :ref:`register an open socket to wait for data using a protocol
424 <asyncio-register-socket>` example uses a low-level protocol created by the
425 :meth:`BaseEventLoop.create_connection` method.
426
427 The :ref:`watch a file descriptor for read events
428 <asyncio-watch-read-event>` example uses the low-level
429 :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a
430 socket.
431