blob: 22b7341cb70280867bf0a388a5928fb080a0f1ef [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
Victor Stinner1374bd42014-01-24 15:34:19 +01005++++++++++++++++++++++++
6Streams (high-level API)
7++++++++++++++++++++++++
Victor Stinner24f8ebf2014-01-23 11:05:01 +01008
9Stream functions
10================
11
Victor Stinnerbdd574d2015-02-12 22:49:18 +010012.. coroutinefunction:: open_connection(host=None, port=None, \*, loop=None, limit=None, \*\*kwds)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010013
14 A wrapper for :meth:`~BaseEventLoop.create_connection()` returning a (reader,
15 writer) pair.
16
17 The reader returned is a :class:`StreamReader` instance; the writer is
18 a :class:`StreamWriter` instance.
19
20 The arguments are all the usual arguments to
21 :meth:`BaseEventLoop.create_connection` except *protocol_factory*; most
22 common are positional host and port, with various optional keyword arguments
23 following.
24
25 Additional optional keyword arguments are *loop* (to set the event loop
26 instance to use) and *limit* (to set the buffer limit passed to the
27 :class:`StreamReader`).
28
29 (If you want to customize the :class:`StreamReader` and/or
30 :class:`StreamReaderProtocol` classes, just copy the code -- there's really
31 nothing special here except some convenience.)
32
Yury Selivanov37f15bc2014-02-20 16:20:44 -050033 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010034
Victor Stinnerbdd574d2015-02-12 22:49:18 +010035.. coroutinefunction:: start_server(client_connected_cb, host=None, port=None, \*, loop=None, limit=None, \*\*kwds)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010036
Victor Stinner8ebeb032014-07-11 23:47:40 +020037 Start a socket server, with a callback for each client connected. The return
38 value is the same as :meth:`~BaseEventLoop.create_server()`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010039
Victor Stinner8ebeb032014-07-11 23:47:40 +020040 The *client_connected_cb* parameter is called with two parameters:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010041 *client_reader*, *client_writer*. *client_reader* is a
42 :class:`StreamReader` object, while *client_writer* is a
Victor Stinner8ebeb032014-07-11 23:47:40 +020043 :class:`StreamWriter` object. The *client_connected_cb* parameter can
44 either be a plain callback function or a :ref:`coroutine function
45 <coroutine>`; if it is a coroutine function, it will be automatically
Victor Stinner337e03f2014-08-11 01:11:13 +020046 converted into a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010047
48 The rest of the arguments are all the usual arguments to
49 :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most
Victor Stinner8ebeb032014-07-11 23:47:40 +020050 common are positional *host* and *port*, with various optional keyword
51 arguments following.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010052
53 Additional optional keyword arguments are *loop* (to set the event loop
54 instance to use) and *limit* (to set the buffer limit passed to the
55 :class:`StreamReader`).
56
Yury Selivanov37f15bc2014-02-20 16:20:44 -050057 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010058
Victor Stinnerbdd574d2015-02-12 22:49:18 +010059.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, limit=None, **kwds)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050060
61 A wrapper for :meth:`~BaseEventLoop.create_unix_connection()` returning
62 a (reader, writer) pair.
63
64 See :func:`open_connection` for information about return value and other
65 details.
66
Yury Selivanov37f15bc2014-02-20 16:20:44 -050067 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050068
69 Availability: UNIX.
70
Victor Stinnerbdd574d2015-02-12 22:49:18 +010071.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \*, loop=None, limit=None, **kwds)
Yury Selivanovd3f8e302014-02-20 14:10:02 -050072
73 Start a UNIX Domain Socket server, with a callback for each client connected.
74
75 See :func:`start_server` for information about return value and other
76 details.
77
Yury Selivanov37f15bc2014-02-20 16:20:44 -050078 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050079
80 Availability: UNIX.
81
Victor Stinner24f8ebf2014-01-23 11:05:01 +010082
83StreamReader
84============
85
Victor Stinner08444382014-02-02 22:43:39 +010086.. class:: StreamReader(limit=None, loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010087
88 .. method:: exception()
89
90 Get the exception.
91
92 .. method:: feed_eof()
93
Yury Selivanovd3f8e302014-02-20 14:10:02 -050094 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010095
96 .. method:: feed_data(data)
97
Yury Selivanovd3f8e302014-02-20 14:10:02 -050098 Feed *data* bytes in the internal buffer. Any operations waiting
99 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100100
101 .. method:: set_exception(exc)
102
103 Set the exception.
104
105 .. method:: set_transport(transport)
106
107 Set the transport.
108
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100109 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100110
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500111 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
112 read until EOF and return all read bytes.
113
114 If the EOF was received and the internal buffer is empty,
115 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100116
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500117 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100118
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100119 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100120
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500121 Read one line, where "line" is a sequence of bytes ending with ``\n``.
122
123 If EOF is received, and ``\n`` was not found, the method will
124 return the partial read bytes.
125
126 If the EOF was received and the internal buffer is empty,
127 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100128
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500129 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100130
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100131 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100132
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100133 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
134 the stream is reached before *n* can be read, the
135 :attr:`IncompleteReadError.partial` attribute of the exception contains
136 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100137
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500138 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100139
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500140 .. method:: at_eof()
141
142 Return ``True`` if the buffer is empty and :meth:`feed_eof` was called.
143
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100144
145StreamWriter
146============
147
148.. class:: StreamWriter(transport, protocol, reader, loop)
149
150 Wraps a Transport.
151
152 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
153 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
154 :meth:`drain` which returns an optional :class:`Future` on which you can
155 wait for flow control. It also adds a transport attribute which references
156 the :class:`Transport` directly.
157
158 .. attribute:: transport
159
160 Transport.
161
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100162 .. method:: can_write_eof()
163
164 Return :const:`True` if the transport supports :meth:`write_eof`,
165 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
166
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100167 .. method:: close()
168
169 Close the transport: see :meth:`BaseTransport.close`.
170
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100171 .. coroutinemethod:: drain()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100172
Victor Stinnere7182972014-11-28 17:45:41 +0100173 Let the write buffer of the underlying transport a chance to be flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100174
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200175 The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100176
177 w.write(data)
178 yield from w.drain()
179
Victor Stinnere7182972014-11-28 17:45:41 +0100180 When the size of the transport buffer reaches the high-water limit (the
181 protocol is paused), block until the size of the buffer is drained down
182 to the low-water limit and the protocol is resumed. When there is nothing
183 to wait for, the yield-from continues immediately.
184
185 Yielding from :meth:`drain` gives the opportunity for the loop to
186 schedule the write operation and flush the buffer. It should especially
187 be used when a possibly large amount of data is written to the transport,
188 and the coroutine does not yield-from between calls to :meth:`write`.
Victor Stinnerd71dcbb2014-08-25 17:04:12 +0200189
190 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100191
192 .. method:: get_extra_info(name, default=None)
193
194 Return optional transport information: see
195 :meth:`BaseTransport.get_extra_info`.
196
197 .. method:: write(data)
198
199 Write some *data* bytes to the transport: see
200 :meth:`WriteTransport.write`.
201
202 .. method:: writelines(data)
203
204 Write a list (or any iterable) of data bytes to the transport:
205 see :meth:`WriteTransport.writelines`.
206
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100207 .. method:: write_eof()
208
209 Close the write end of the transport after flushing buffered data:
210 see :meth:`WriteTransport.write_eof`.
211
212
213StreamReaderProtocol
214====================
215
216.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None)
217
218 Trivial helper class to adapt between :class:`Protocol` and
219 :class:`StreamReader`. Sublclass of :class:`Protocol`.
220
221 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
222 is an optional function called with (stream_reader, stream_writer) when a
223 connection is made, *loop* is the event loop instance to use.
224
225 (This is a helper class instead of making :class:`StreamReader` itself a
226 :class:`Protocol` subclass, because the :class:`StreamReader` has other
227 potential uses, and to prevent the user of the :class:`StreamReader` to
228 accidentally call inappropriate methods of the protocol.)
229
Victor Stinnerc520edc2014-01-23 11:25:48 +0100230
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100231IncompleteReadError
232===================
233
234.. exception:: IncompleteReadError
235
Victor Stinner32970b82014-01-27 12:18:49 +0100236 Incomplete read error, subclass of :exc:`EOFError`.
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100237
238 .. attribute:: expected
239
240 Total number of expected bytes (:class:`int`).
241
242 .. attribute:: partial
243
244 Read bytes string before the end of stream was reached (:class:`bytes`).
245
246
Victor Stinner5121a9b2014-10-11 15:52:14 +0200247Stream examples
248===============
249
Victor Stinnered051592014-10-12 20:18:16 +0200250.. _asyncio-tcp-echo-client-streams:
251
252TCP echo client using streams
253-----------------------------
254
255TCP echo client using the :func:`asyncio.open_connection` function::
256
257 import asyncio
258
Victor Stinnered8e3a92014-10-13 00:55:50 +0200259 @asyncio.coroutine
Victor Stinnered051592014-10-12 20:18:16 +0200260 def tcp_echo_client(message, loop):
261 reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888,
262 loop=loop)
263
264 print('Send: %r' % message)
265 writer.write(message.encode())
266
267 data = yield from reader.read(100)
268 print('Received: %r' % data.decode())
269
270 print('Close the socket')
271 writer.close()
272
273 message = 'Hello World!'
274 loop = asyncio.get_event_loop()
275 loop.run_until_complete(tcp_echo_client(message, loop))
276 loop.close()
277
278.. seealso::
279
280 The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
281 example uses the :meth:`BaseEventLoop.create_connection` method.
282
283
284.. _asyncio-tcp-echo-server-streams:
285
286TCP echo server using streams
287-----------------------------
288
289TCP echo server using the :func:`asyncio.start_server` function::
290
291 import asyncio
292
293 @asyncio.coroutine
294 def handle_echo(reader, writer):
295 data = yield from reader.read(100)
296 message = data.decode()
297 addr = writer.get_extra_info('peername')
298 print("Received %r from %r" % (message, addr))
299
300 print("Send: %r" % message)
301 writer.write(data)
302 yield from writer.drain()
303
304 print("Close the client socket")
305 writer.close()
306
307 loop = asyncio.get_event_loop()
308 coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
309 server = loop.run_until_complete(coro)
310
311 # Serve requests until CTRL+c is pressed
312 print('Serving on {}'.format(server.sockets[0].getsockname()))
313 try:
314 loop.run_forever()
315 except KeyboardInterrupt:
316 pass
317
318 # Close the server
319 server.close()
320 loop.run_until_complete(server.wait_closed())
321 loop.close()
322
323.. seealso::
324
325 The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
326 example uses the :meth:`BaseEventLoop.create_server` method.
327
328
Victor Stinner5121a9b2014-10-11 15:52:14 +0200329Get HTTP headers
330----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100331
332Simple example querying HTTP headers of the URL passed on the command line::
333
334 import asyncio
335 import urllib.parse
336 import sys
337
338 @asyncio.coroutine
339 def print_http_headers(url):
340 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200341 if url.scheme == 'https':
342 connect = asyncio.open_connection(url.hostname, 443, ssl=True)
343 else:
344 connect = asyncio.open_connection(url.hostname, 80)
345 reader, writer = yield from connect
346 query = ('HEAD {path} HTTP/1.0\r\n'
347 'Host: {hostname}\r\n'
348 '\r\n').format(path=url.path or '/', hostname=url.hostname)
Victor Stinnerc520edc2014-01-23 11:25:48 +0100349 writer.write(query.encode('latin-1'))
350 while True:
351 line = yield from reader.readline()
352 if not line:
353 break
354 line = line.decode('latin1').rstrip()
355 if line:
356 print('HTTP header> %s' % line)
357
Victor Stinner5121a9b2014-10-11 15:52:14 +0200358 # Ignore the body, close the socket
359 writer.close()
360
Victor Stinnerc520edc2014-01-23 11:25:48 +0100361 url = sys.argv[1]
362 loop = asyncio.get_event_loop()
363 task = asyncio.async(print_http_headers(url))
364 loop.run_until_complete(task)
Victor Stinnerf40c6632014-01-28 23:32:40 +0100365 loop.close()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100366
367Usage::
368
369 python example.py http://example.com/path/page.html
370
Victor Stinner04e6df32014-10-11 16:16:27 +0200371or with HTTPS::
372
373 python example.py https://example.com/path/page.html
374
375.. _asyncio-register-socket-streams:
376
377Register an open socket to wait for data using streams
378------------------------------------------------------
379
380Coroutine waiting until a socket receives data using the
381:func:`open_connection` function::
382
383 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200384 try:
385 from socket import socketpair
386 except ImportError:
387 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200388
Victor Stinnered8e3a92014-10-13 00:55:50 +0200389 @asyncio.coroutine
Victor Stinner04e6df32014-10-11 16:16:27 +0200390 def wait_for_data(loop):
391 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200392 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200393
394 # Register the open socket to wait for data
395 reader, writer = yield from asyncio.open_connection(sock=rsock, loop=loop)
396
397 # Simulate the reception of data from the network
398 loop.call_soon(wsock.send, 'abc'.encode())
399
400 # Wait for data
401 data = yield from reader.read(100)
402
403 # Got data, we are done: close the socket
404 print("Received:", data.decode())
405 writer.close()
406
407 # Close the second socket
408 wsock.close()
409
410 loop = asyncio.get_event_loop()
411 loop.run_until_complete(wait_for_data(loop))
412 loop.close()
413
414.. seealso::
415
416 The :ref:`register an open socket to wait for data using a protocol
417 <asyncio-register-socket>` example uses a low-level protocol created by the
418 :meth:`BaseEventLoop.create_connection` method.
419
420 The :ref:`watch a file descriptor for read events
421 <asyncio-watch-read-event>` example uses the low-level
422 :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a
423 socket.
424