Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 1 | .. currentmodule:: asyncio |
| 2 | |
Victor Stinner | 9592edb | 2014-02-02 15:03:02 +0100 | [diff] [blame] | 3 | .. _asyncio-streams: |
Victor Stinner | 4b4f9eb | 2014-01-24 17:33:20 +0100 | [diff] [blame] | 4 | |
Victor Stinner | 1374bd4 | 2014-01-24 15:34:19 +0100 | [diff] [blame] | 5 | ++++++++++++++++++++++++ |
| 6 | Streams (high-level API) |
| 7 | ++++++++++++++++++++++++ |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 8 | |
| 9 | Stream functions |
| 10 | ================ |
| 11 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 12 | .. coroutinefunction:: open_connection(host=None, port=None, \*, loop=None, limit=None, \*\*kwds) |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 13 | |
| 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 Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 33 | This function is a :ref:`coroutine <coroutine>`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 34 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 35 | .. coroutinefunction:: start_server(client_connected_cb, host=None, port=None, \*, loop=None, limit=None, \*\*kwds) |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 36 | |
Victor Stinner | 8ebeb03 | 2014-07-11 23:47:40 +0200 | [diff] [blame] | 37 | Start a socket server, with a callback for each client connected. The return |
| 38 | value is the same as :meth:`~BaseEventLoop.create_server()`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 39 | |
Victor Stinner | 8ebeb03 | 2014-07-11 23:47:40 +0200 | [diff] [blame] | 40 | The *client_connected_cb* parameter is called with two parameters: |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 41 | *client_reader*, *client_writer*. *client_reader* is a |
| 42 | :class:`StreamReader` object, while *client_writer* is a |
Victor Stinner | 8ebeb03 | 2014-07-11 23:47:40 +0200 | [diff] [blame] | 43 | :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 Stinner | 337e03f | 2014-08-11 01:11:13 +0200 | [diff] [blame] | 46 | converted into a :class:`Task`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 47 | |
| 48 | The rest of the arguments are all the usual arguments to |
| 49 | :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most |
Victor Stinner | 8ebeb03 | 2014-07-11 23:47:40 +0200 | [diff] [blame] | 50 | common are positional *host* and *port*, with various optional keyword |
| 51 | arguments following. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 52 | |
| 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 Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 57 | This function is a :ref:`coroutine <coroutine>`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 58 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 59 | .. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, limit=None, **kwds) |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 60 | |
| 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 Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 67 | This function is a :ref:`coroutine <coroutine>`. |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 68 | |
| 69 | Availability: UNIX. |
| 70 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 71 | .. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \*, loop=None, limit=None, **kwds) |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 72 | |
| 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 Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 78 | This function is a :ref:`coroutine <coroutine>`. |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 79 | |
| 80 | Availability: UNIX. |
| 81 | |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 82 | |
| 83 | StreamReader |
| 84 | ============ |
| 85 | |
Victor Stinner | 0844438 | 2014-02-02 22:43:39 +0100 | [diff] [blame] | 86 | .. class:: StreamReader(limit=None, loop=None) |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 87 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 88 | This class is :ref:`not thread safe <asyncio-multithreading>`. |
| 89 | |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 90 | .. method:: exception() |
| 91 | |
| 92 | Get the exception. |
| 93 | |
| 94 | .. method:: feed_eof() |
| 95 | |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 96 | Acknowledge the EOF. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 97 | |
| 98 | .. method:: feed_data(data) |
| 99 | |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 100 | Feed *data* bytes in the internal buffer. Any operations waiting |
| 101 | for the data will be resumed. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 102 | |
| 103 | .. method:: set_exception(exc) |
| 104 | |
| 105 | Set the exception. |
| 106 | |
| 107 | .. method:: set_transport(transport) |
| 108 | |
| 109 | Set the transport. |
| 110 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 111 | .. coroutinemethod:: read(n=-1) |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 112 | |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 113 | Read up to *n* bytes. If *n* is not provided, or set to ``-1``, |
| 114 | read until EOF and return all read bytes. |
| 115 | |
| 116 | If the EOF was received and the internal buffer is empty, |
| 117 | return an empty ``bytes`` object. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 118 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 119 | This method is a :ref:`coroutine <coroutine>`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 120 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 121 | .. coroutinemethod:: readline() |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 122 | |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 123 | Read one line, where "line" is a sequence of bytes ending with ``\n``. |
| 124 | |
| 125 | If EOF is received, and ``\n`` was not found, the method will |
| 126 | return the partial read bytes. |
| 127 | |
| 128 | If the EOF was received and the internal buffer is empty, |
| 129 | return an empty ``bytes`` object. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 130 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 131 | This method is a :ref:`coroutine <coroutine>`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 132 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 133 | .. coroutinemethod:: readexactly(n) |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 134 | |
Victor Stinner | b7f19ff | 2014-01-27 11:58:49 +0100 | [diff] [blame] | 135 | Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of |
| 136 | the stream is reached before *n* can be read, the |
| 137 | :attr:`IncompleteReadError.partial` attribute of the exception contains |
| 138 | the partial read bytes. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 139 | |
Yury Selivanov | 37f15bc | 2014-02-20 16:20:44 -0500 | [diff] [blame] | 140 | This method is a :ref:`coroutine <coroutine>`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 141 | |
Yury Selivanov | d3f8e30 | 2014-02-20 14:10:02 -0500 | [diff] [blame] | 142 | .. method:: at_eof() |
| 143 | |
| 144 | Return ``True`` if the buffer is empty and :meth:`feed_eof` was called. |
| 145 | |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 146 | |
| 147 | StreamWriter |
| 148 | ============ |
| 149 | |
| 150 | .. class:: StreamWriter(transport, protocol, reader, loop) |
| 151 | |
| 152 | Wraps a Transport. |
| 153 | |
| 154 | This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`, |
| 155 | :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds |
| 156 | :meth:`drain` which returns an optional :class:`Future` on which you can |
| 157 | wait for flow control. It also adds a transport attribute which references |
| 158 | the :class:`Transport` directly. |
| 159 | |
Victor Stinner | 8370496 | 2015-02-25 14:24:15 +0100 | [diff] [blame] | 160 | This class is :ref:`not thread safe <asyncio-multithreading>`. |
| 161 | |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 162 | .. attribute:: transport |
| 163 | |
| 164 | Transport. |
| 165 | |
Victor Stinner | ffbe3c6 | 2014-02-08 22:50:07 +0100 | [diff] [blame] | 166 | .. method:: can_write_eof() |
| 167 | |
| 168 | Return :const:`True` if the transport supports :meth:`write_eof`, |
| 169 | :const:`False` if not. See :meth:`WriteTransport.can_write_eof`. |
| 170 | |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 171 | .. method:: close() |
| 172 | |
| 173 | Close the transport: see :meth:`BaseTransport.close`. |
| 174 | |
Victor Stinner | bdd574d | 2015-02-12 22:49:18 +0100 | [diff] [blame] | 175 | .. coroutinemethod:: drain() |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 176 | |
Victor Stinner | e718297 | 2014-11-28 17:45:41 +0100 | [diff] [blame] | 177 | Let the write buffer of the underlying transport a chance to be flushed. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 178 | |
Victor Stinner | d71dcbb | 2014-08-25 17:04:12 +0200 | [diff] [blame] | 179 | The intended use is to write:: |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 180 | |
| 181 | w.write(data) |
| 182 | yield from w.drain() |
| 183 | |
Victor Stinner | e718297 | 2014-11-28 17:45:41 +0100 | [diff] [blame] | 184 | When the size of the transport buffer reaches the high-water limit (the |
| 185 | protocol is paused), block until the size of the buffer is drained down |
| 186 | to the low-water limit and the protocol is resumed. When there is nothing |
| 187 | to wait for, the yield-from continues immediately. |
| 188 | |
| 189 | Yielding from :meth:`drain` gives the opportunity for the loop to |
| 190 | schedule the write operation and flush the buffer. It should especially |
| 191 | be used when a possibly large amount of data is written to the transport, |
| 192 | and the coroutine does not yield-from between calls to :meth:`write`. |
Victor Stinner | d71dcbb | 2014-08-25 17:04:12 +0200 | [diff] [blame] | 193 | |
| 194 | This method is a :ref:`coroutine <coroutine>`. |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 195 | |
| 196 | .. method:: get_extra_info(name, default=None) |
| 197 | |
| 198 | Return optional transport information: see |
| 199 | :meth:`BaseTransport.get_extra_info`. |
| 200 | |
| 201 | .. method:: write(data) |
| 202 | |
| 203 | Write some *data* bytes to the transport: see |
| 204 | :meth:`WriteTransport.write`. |
| 205 | |
| 206 | .. method:: writelines(data) |
| 207 | |
| 208 | Write a list (or any iterable) of data bytes to the transport: |
| 209 | see :meth:`WriteTransport.writelines`. |
| 210 | |
Victor Stinner | 24f8ebf | 2014-01-23 11:05:01 +0100 | [diff] [blame] | 211 | .. method:: write_eof() |
| 212 | |
| 213 | Close the write end of the transport after flushing buffered data: |
| 214 | see :meth:`WriteTransport.write_eof`. |
| 215 | |
| 216 | |
| 217 | StreamReaderProtocol |
| 218 | ==================== |
| 219 | |
| 220 | .. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None) |
| 221 | |
| 222 | Trivial helper class to adapt between :class:`Protocol` and |
| 223 | :class:`StreamReader`. Sublclass of :class:`Protocol`. |
| 224 | |
| 225 | *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb* |
| 226 | is an optional function called with (stream_reader, stream_writer) when a |
| 227 | connection is made, *loop* is the event loop instance to use. |
| 228 | |
| 229 | (This is a helper class instead of making :class:`StreamReader` itself a |
| 230 | :class:`Protocol` subclass, because the :class:`StreamReader` has other |
| 231 | potential uses, and to prevent the user of the :class:`StreamReader` to |
| 232 | accidentally call inappropriate methods of the protocol.) |
| 233 | |
Victor Stinner | c520edc | 2014-01-23 11:25:48 +0100 | [diff] [blame] | 234 | |
Victor Stinner | b7f19ff | 2014-01-27 11:58:49 +0100 | [diff] [blame] | 235 | IncompleteReadError |
| 236 | =================== |
| 237 | |
| 238 | .. exception:: IncompleteReadError |
| 239 | |
Victor Stinner | 32970b8 | 2014-01-27 12:18:49 +0100 | [diff] [blame] | 240 | Incomplete read error, subclass of :exc:`EOFError`. |
Victor Stinner | b7f19ff | 2014-01-27 11:58:49 +0100 | [diff] [blame] | 241 | |
| 242 | .. attribute:: expected |
| 243 | |
| 244 | Total number of expected bytes (:class:`int`). |
| 245 | |
| 246 | .. attribute:: partial |
| 247 | |
| 248 | Read bytes string before the end of stream was reached (:class:`bytes`). |
| 249 | |
| 250 | |
Victor Stinner | 5121a9b | 2014-10-11 15:52:14 +0200 | [diff] [blame] | 251 | Stream examples |
| 252 | =============== |
| 253 | |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 254 | .. _asyncio-tcp-echo-client-streams: |
| 255 | |
| 256 | TCP echo client using streams |
| 257 | ----------------------------- |
| 258 | |
| 259 | TCP echo client using the :func:`asyncio.open_connection` function:: |
| 260 | |
| 261 | import asyncio |
| 262 | |
Victor Stinner | ed8e3a9 | 2014-10-13 00:55:50 +0200 | [diff] [blame] | 263 | @asyncio.coroutine |
Victor Stinner | ed05159 | 2014-10-12 20:18:16 +0200 | [diff] [blame] | 264 | def tcp_echo_client(message, loop): |
| 265 | reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888, |
| 266 | loop=loop) |
| 267 | |
| 268 | print('Send: %r' % message) |
| 269 | writer.write(message.encode()) |
| 270 | |
| 271 | data = yield from reader.read(100) |
| 272 | print('Received: %r' % data.decode()) |
| 273 | |
| 274 | print('Close the socket') |
| 275 | writer.close() |
| 276 | |
| 277 | message = 'Hello World!' |
| 278 | loop = asyncio.get_event_loop() |
| 279 | loop.run_until_complete(tcp_echo_client(message, loop)) |
| 280 | loop.close() |
| 281 | |
| 282 | .. seealso:: |
| 283 | |
| 284 | The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>` |
| 285 | example uses the :meth:`BaseEventLoop.create_connection` method. |
| 286 | |
| 287 | |
| 288 | .. _asyncio-tcp-echo-server-streams: |
| 289 | |
| 290 | TCP echo server using streams |
| 291 | ----------------------------- |
| 292 | |
| 293 | TCP echo server using the :func:`asyncio.start_server` function:: |
| 294 | |
| 295 | import asyncio |
| 296 | |
| 297 | @asyncio.coroutine |
| 298 | def handle_echo(reader, writer): |
| 299 | data = yield from reader.read(100) |
| 300 | message = data.decode() |
| 301 | addr = writer.get_extra_info('peername') |
| 302 | print("Received %r from %r" % (message, addr)) |
| 303 | |
| 304 | print("Send: %r" % message) |
| 305 | writer.write(data) |
| 306 | yield from writer.drain() |
| 307 | |
| 308 | print("Close the client socket") |
| 309 | writer.close() |
| 310 | |
| 311 | loop = asyncio.get_event_loop() |
| 312 | coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop) |
| 313 | server = loop.run_until_complete(coro) |
| 314 | |
| 315 | # Serve requests until CTRL+c is pressed |
| 316 | print('Serving on {}'.format(server.sockets[0].getsockname())) |
| 317 | try: |
| 318 | loop.run_forever() |
| 319 | except KeyboardInterrupt: |
| 320 | pass |
| 321 | |
| 322 | # Close the server |
| 323 | server.close() |
| 324 | loop.run_until_complete(server.wait_closed()) |
| 325 | loop.close() |
| 326 | |
| 327 | .. seealso:: |
| 328 | |
| 329 | The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>` |
| 330 | example uses the :meth:`BaseEventLoop.create_server` method. |
| 331 | |
| 332 | |
Victor Stinner | 5121a9b | 2014-10-11 15:52:14 +0200 | [diff] [blame] | 333 | Get HTTP headers |
| 334 | ---------------- |
Victor Stinner | c520edc | 2014-01-23 11:25:48 +0100 | [diff] [blame] | 335 | |
| 336 | Simple example querying HTTP headers of the URL passed on the command line:: |
| 337 | |
| 338 | import asyncio |
| 339 | import urllib.parse |
| 340 | import sys |
| 341 | |
| 342 | @asyncio.coroutine |
| 343 | def print_http_headers(url): |
| 344 | url = urllib.parse.urlsplit(url) |
Victor Stinner | 5121a9b | 2014-10-11 15:52:14 +0200 | [diff] [blame] | 345 | if url.scheme == 'https': |
| 346 | connect = asyncio.open_connection(url.hostname, 443, ssl=True) |
| 347 | else: |
| 348 | connect = asyncio.open_connection(url.hostname, 80) |
| 349 | reader, writer = yield from connect |
| 350 | query = ('HEAD {path} HTTP/1.0\r\n' |
| 351 | 'Host: {hostname}\r\n' |
| 352 | '\r\n').format(path=url.path or '/', hostname=url.hostname) |
Victor Stinner | c520edc | 2014-01-23 11:25:48 +0100 | [diff] [blame] | 353 | writer.write(query.encode('latin-1')) |
| 354 | while True: |
| 355 | line = yield from reader.readline() |
| 356 | if not line: |
| 357 | break |
| 358 | line = line.decode('latin1').rstrip() |
| 359 | if line: |
| 360 | print('HTTP header> %s' % line) |
| 361 | |
Victor Stinner | 5121a9b | 2014-10-11 15:52:14 +0200 | [diff] [blame] | 362 | # Ignore the body, close the socket |
| 363 | writer.close() |
| 364 | |
Victor Stinner | c520edc | 2014-01-23 11:25:48 +0100 | [diff] [blame] | 365 | url = sys.argv[1] |
| 366 | loop = asyncio.get_event_loop() |
Yury Selivanov | d7e19bb | 2015-05-11 16:33:41 -0400 | [diff] [blame] | 367 | task = asyncio.ensure_future(print_http_headers(url)) |
Victor Stinner | c520edc | 2014-01-23 11:25:48 +0100 | [diff] [blame] | 368 | loop.run_until_complete(task) |
Victor Stinner | f40c663 | 2014-01-28 23:32:40 +0100 | [diff] [blame] | 369 | loop.close() |
Victor Stinner | c520edc | 2014-01-23 11:25:48 +0100 | [diff] [blame] | 370 | |
| 371 | Usage:: |
| 372 | |
| 373 | python example.py http://example.com/path/page.html |
| 374 | |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 375 | or with HTTPS:: |
| 376 | |
| 377 | python example.py https://example.com/path/page.html |
| 378 | |
| 379 | .. _asyncio-register-socket-streams: |
| 380 | |
| 381 | Register an open socket to wait for data using streams |
| 382 | ------------------------------------------------------ |
| 383 | |
| 384 | Coroutine waiting until a socket receives data using the |
| 385 | :func:`open_connection` function:: |
| 386 | |
| 387 | import asyncio |
Victor Stinner | ccd8e34 | 2014-10-11 16:30:02 +0200 | [diff] [blame] | 388 | try: |
| 389 | from socket import socketpair |
| 390 | except ImportError: |
| 391 | from asyncio.windows_utils import socketpair |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 392 | |
Victor Stinner | ed8e3a9 | 2014-10-13 00:55:50 +0200 | [diff] [blame] | 393 | @asyncio.coroutine |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 394 | def wait_for_data(loop): |
| 395 | # Create a pair of connected sockets |
Victor Stinner | ccd8e34 | 2014-10-11 16:30:02 +0200 | [diff] [blame] | 396 | rsock, wsock = socketpair() |
Victor Stinner | 04e6df3 | 2014-10-11 16:16:27 +0200 | [diff] [blame] | 397 | |
| 398 | # Register the open socket to wait for data |
| 399 | reader, writer = yield from asyncio.open_connection(sock=rsock, loop=loop) |
| 400 | |
| 401 | # Simulate the reception of data from the network |
| 402 | loop.call_soon(wsock.send, 'abc'.encode()) |
| 403 | |
| 404 | # Wait for data |
| 405 | data = yield from reader.read(100) |
| 406 | |
| 407 | # Got data, we are done: close the socket |
| 408 | print("Received:", data.decode()) |
| 409 | writer.close() |
| 410 | |
| 411 | # Close the second socket |
| 412 | wsock.close() |
| 413 | |
| 414 | loop = asyncio.get_event_loop() |
| 415 | loop.run_until_complete(wait_for_data(loop)) |
| 416 | loop.close() |
| 417 | |
| 418 | .. seealso:: |
| 419 | |
| 420 | The :ref:`register an open socket to wait for data using a protocol |
| 421 | <asyncio-register-socket>` example uses a low-level protocol created by the |
| 422 | :meth:`BaseEventLoop.create_connection` method. |
| 423 | |
| 424 | The :ref:`watch a file descriptor for read events |
| 425 | <asyncio-watch-read-event>` example uses the low-level |
| 426 | :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a |
| 427 | socket. |
| 428 | |