blob: e3a56568a6f95d984330593a9b110454e12703d0 [file] [log] [blame]
Victor Stinnerea3183f2013-12-03 01:08:00 +01001.. module:: asyncio
2
Victor Stinner1ca5ba62013-12-03 01:49:43 +01003++++++++++++++++++++++++
4Transports and protocols
5++++++++++++++++++++++++
6
Victor Stinnerea3183f2013-12-03 01:08:00 +01007.. _transport:
8
9Transports
10==========
11
12Transports are classed provided by :mod:`asyncio` in order to abstract
13various kinds of communication channels. You generally won't instantiate
14a transport yourself; instead, you will call a :class:`BaseEventLoop` method
15which will create the transport and try to initiate the underlying
16communication channel, calling you back when it succeeds.
17
18Once the communication channel is established, a transport is always
19paired with a :ref:`protocol <protocol>` instance. The protocol can
20then call the transport's methods for various purposes.
21
22:mod:`asyncio` currently implements transports for TCP, UDP, SSL, and
23subprocess pipes. The methods available on a transport depend on
24the transport's kind.
25
26
Victor Stinner0c6f1ca2013-12-03 01:46:39 +010027BaseTransport
28-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010029
30.. class:: BaseTransport
31
32 Base class for transports.
33
34 .. method:: close(self)
35
36 Close the transport. If the transport has a buffer for outgoing
37 data, buffered data will be flushed asynchronously. No more data
38 will be received. After all buffered data is flushed, the
39 protocol's :meth:`connection_lost` method will be called with
40 :const:`None` as its argument.
41
42
43 .. method:: get_extra_info(name, default=None)
44
45 Return optional transport information. *name* is a string representing
46 the piece of transport-specific information to get, *default* is the
47 value to return if the information doesn't exist.
48
49 This method allows transport implementations to easily expose
50 channel-specific information.
51
52 * socket:
53
54 - ``'peername'``: the remote address to which the socket is connected,
55 result of :meth:`socket.socket.getpeername` (``None`` on error)
56 - ``'socket'``: :class:`socket.socket` instance
57 - ``'sockname'``: the socket's own address,
58 result of :meth:`socket.socket.getsockname`
59
60 * SSL socket:
61
62 - ``'compression'``: the compression algorithm being used as a string,
63 or ``None`` if the connection isn't compressed; result of
64 :meth:`ssl.SSLSocket.compression`
65 - ``'cipher'``: a three-value tuple containing the name of the cipher
66 being used, the version of the SSL protocol that defines its use, and
67 the number of secret bits being used; result of
68 :meth:`ssl.SSLSocket.cipher`
69 - ``'peercert'``: peer certificate; result of
70 :meth:`ssl.SSLSocket.getpeercert`
71 - ``'sslcontext'``: :class:`ssl.SSLContext` instance
72
73 * pipe:
74
75 - ``'pipe'``: pipe object
76
77 * subprocess:
78
79 - ``'subprocess'``: :class:`subprocess.Popen` instance
80
81
Victor Stinner0c6f1ca2013-12-03 01:46:39 +010082ReadTransport
83-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010084
85.. class:: ReadTransport
86
87 Interface for read-only transports.
88
89 .. method:: pause_reading()
90
91 Pause the receiving end of the transport. No data will be passed to
92 the protocol's :meth:`data_received` method until meth:`resume_reading`
93 is called.
94
95 .. method:: resume_reading()
96
97 Resume the receiving end. The protocol's :meth:`data_received` method
98 will be called once again if some data is available for reading.
99
100
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100101WriteTransport
102--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100103
104.. class:: WriteTransport
105
106 Interface for write-only transports.
107
108 .. method:: abort()
109
110 Close the transport immediately, without waiting for pending operations
111 to complete. Buffered data will be lost. No more data will be received.
112 The protocol's :meth:`connection_lost` method will eventually be
113 called with :const:`None` as its argument.
114
115 .. method:: can_write_eof()
116
117 Return :const:`True` if the transport supports :meth:`write_eof`,
118 :const:`False` if not.
119
120 .. method:: get_write_buffer_size()
121
122 Return the current size of the output buffer used by the transport.
123
124 .. method:: set_write_buffer_limits(high=None, low=None)
125
126 Set the *high*- and *low*-water limits for write flow control.
127
128 These two values control when call the protocol's
129 :meth:`pause_writing` and :meth:`resume_writing` methods are called.
130 If specified, the low-water limit must be less than or equal to the
131 high-water limit. Neither *high* nor *low* can be negative.
132
133 The defaults are implementation-specific. If only the
134 high-water limit is given, the low-water limit defaults to a
135 implementation-specific value less than or equal to the
136 high-water limit. Setting *high* to zero forces *low* to zero as
137 well, and causes :meth:`pause_writing` to be called whenever the
138 buffer becomes non-empty. Setting *low* to zero causes
139 :meth:`resume_writing` to be called only once the buffer is empty.
140 Use of zero for either limit is generally sub-optimal as it
141 reduces opportunities for doing I/O and computation
142 concurrently.
143
144 .. method:: write(data)
145
146 Write some *data* bytes to the transport.
147
148 This method does not block; it buffers the data and arranges for it
149 to be sent out asynchronously.
150
151 .. method:: writelines(list_of_data)
152
153 Write a list (or any iterable) of data bytes to the transport.
154 This is functionally equivalent to calling :meth:`write` on each
155 element yielded by the iterable, but may be implemented more efficiently.
156
157 .. method:: write_eof()
158
159 Close the write end of the transport after flushing buffered data.
160 Data may still be received.
161
162 This method can raise :exc:`NotImplementedError` if the transport
163 (e.g. SSL) doesn't support half-closes.
164
165
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100166DatagramTransport
167-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
169.. method:: DatagramTransport.sendto(data, addr=None)
170
171 Send the *data* bytes to the remote peer given by *addr* (a
172 transport-dependent target address). If *addr* is :const:`None`, the
173 data is sent to the target address given on transport creation.
174
175 This method does not block; it buffers the data and arranges for it
176 to be sent out asynchronously.
177
178.. method:: DatagramTransport.abort()
179
180 Close the transport immediately, without waiting for pending operations
181 to complete. Buffered data will be lost. No more data will be received.
182 The protocol's :meth:`connection_lost` method will eventually be
183 called with :const:`None` as its argument.
184
185
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100186BaseSubprocessTransport
187-----------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100188
189.. class:: BaseSubprocessTransport
190
191 .. method:: get_pid()
192
193 Return the subprocess process id as an integer.
194
Victor Stinnerea3183f2013-12-03 01:08:00 +0100195 .. method:: get_pipe_transport(fd)
196
197 Return the transport for the communication pipe correspondong to the
198 integer file descriptor *fd*. The return value can be a readable or
199 writable streaming transport, depending on the *fd*. If *fd* doesn't
200 correspond to a pipe belonging to this transport, :const:`None` is
201 returned.
202
Victor Stinner933a8c82013-12-03 01:59:38 +0100203 .. method:: get_returncode()
204
205 Return the subprocess returncode as an integer or :const:`None`
206 if it hasn't returned, similarly to the
207 :attr:`subprocess.Popen.returncode` attribute.
208
209 .. method:: kill(self)
210
211 Kill the subprocess, as in :meth:`subprocess.Popen.kill`
212
213 On POSIX systems, the function sends SIGKILL to the subprocess.
214 On Windows, this method is an alias for :meth:`terminate`.
215
Victor Stinnerea3183f2013-12-03 01:08:00 +0100216 .. method:: send_signal(signal)
217
218 Send the *signal* number to the subprocess, as in
219 :meth:`subprocess.Popen.send_signal`.
220
221 .. method:: terminate()
222
223 Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`.
224 This method is an alias for the :meth:`close` method.
225
226 On POSIX systems, this method sends SIGTERM to the subprocess.
227 On Windows, the Windows API function TerminateProcess() is called to
228 stop the subprocess.
229
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100231StreamWriter
232------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100233
234.. class:: StreamWriter(transport, protocol, reader, loop)
235
236 Wraps a Transport.
237
238 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`, :meth:`write_eof`, :meth:`get_extra_info` and
239 :meth:`close`. It adds :meth:`drain` which returns an optional :class:`~concurrent.futures.Future` on which you can
240 wait for flow control. It also adds a transport attribute which references
241 the :class:`Transport` directly.
242
243 .. attribute:: transport
244
245 Transport.
246
247 .. method:: close()
248
249 Close the transport: see :meth:`BaseTransport.close`.
250
251 .. method:: drain()
252
253 This method has an unusual return value.
254
255 The intended use is to write::
256
257 w.write(data)
258 yield from w.drain()
259
260 When there's nothing to wait for, :meth:`drain()` returns ``()``, and the
261 yield-from continues immediately. When the transport buffer is full (the
262 protocol is paused), :meth:`drain` creates and returns a
263 :class:`~concurrent.futures.Future` and the yield-from will block until
264 that Future is completed, which will happen when the buffer is
265 (partially) drained and the protocol is resumed.
266
267 .. method:: get_extra_info(name, default=None)
268
269 Return optional transport information: see
270 :meth:`BaseTransport.get_extra_info`.
271
272 .. method:: write(data)
273
274 Write some *data* bytes to the transport: see
275 :meth:`WriteTransport.write`.
276
277 .. method:: writelines(data)
278
279 Write a list (or any iterable) of data bytes to the transport:
280 see :meth:`WriteTransport.writelines`.
281
282 .. method:: can_write_eof()
283
284 Return :const:`True` if the transport supports :meth:`write_eof`,
285 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
286
287 .. method:: write_eof()
288
289 Close the write end of the transport after flushing buffered data:
290 see :meth:`WriteTransport.write_eof`.
291
292
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100293StreamReader
294------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100295
296.. class:: StreamReader(limit=_DEFAULT_LIMIT, loop=None)
297
298 .. method:: exception()
299
300 Get the exception.
301
302 .. method:: feed_eof()
303
304 XXX
305
306 .. method:: feed_data(data)
307
308 XXX
309
310 .. method:: set_exception(exc)
311
312 Set the exception.
313
314 .. method:: set_transport(transport)
315
316 Set the transport.
317
318 .. method:: read(n=-1)
319
320 XXX
321
322 This method returns a :ref:`coroutine <coroutine>`.
323
324 .. method:: readline()
325
326 XXX
327
328 This method returns a :ref:`coroutine <coroutine>`.
329
330 .. method:: readexactly(n)
331
332 XXX
333
334 This method returns a :ref:`coroutine <coroutine>`.
335
336
337
338.. _protocol:
339
340Protocols
341=========
342
343:mod:`asyncio` provides base classes that you can subclass to implement
344your network protocols. Those classes are used in conjunction with
345:ref:`transports <transport>` (see below): the protocol parses incoming
346data and asks for the writing of outgoing data, while the transport is
347responsible for the actual I/O and buffering.
348
349When subclassing a protocol class, it is recommended you override certain
350methods. Those methods are callbacks: they will be called by the transport
351on certain events (for example when some data is received); you shouldn't
352call them yourself, unless you are implementing a transport.
353
354.. note::
355 All callbacks have default implementations, which are empty. Therefore,
356 you only need to implement the callbacks for the events in which you
357 are interested.
358
359
360Protocol classes
361----------------
362
363.. class:: Protocol
364
365 The base class for implementing streaming protocols (for use with
366 e.g. TCP and SSL transports).
367
368.. class:: DatagramProtocol
369
370 The base class for implementing datagram protocols (for use with
371 e.g. UDP transports).
372
373.. class:: SubprocessProtocol
374
375 The base class for implementing protocols communicating with child
376 processes (through a set of unidirectional pipes).
377
378
379Connection callbacks
380--------------------
381
382These callbacks may be called on :class:`Protocol` and
383:class:`SubprocessProtocol` instances:
384
385.. method:: BaseProtocol.connection_made(transport)
386
387 Called when a connection is made.
388
389 The *transport* argument is the transport representing the
390 connection. You are responsible for storing it somewhere
391 (e.g. as an attribute) if you need to.
392
393.. method:: BaseProtocol.connection_lost(exc)
394
395 Called when the connection is lost or closed.
396
397 The argument is either an exception object or :const:`None`.
398 The latter means a regular EOF is received, or the connection was
399 aborted or closed by this side of the connection.
400
401:meth:`connection_made` and :meth:`connection_lost` are called exactly once
402per successful connection. All other callbacks will be called between those
403two methods, which allows for easier resource management in your protocol
404implementation.
405
406The following callbacks may be called only on :class:`SubprocessProtocol`
407instances:
408
409.. method:: SubprocessProtocol.pipe_data_received(fd, data)
410
411 Called when the child process writes data into its stdout or stderr pipe.
412 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
413 bytes object containing the data.
414
415.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
416
417 Called when one of the pipes communicating with the child process
418 is closed. *fd* is the integer file descriptor that was closed.
419
420.. method:: SubprocessProtocol.process_exited()
421
422 Called when the child process has exited.
423
424
Victor Stinnerea3183f2013-12-03 01:08:00 +0100425Streaming protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100426-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100427
428The following callbacks are called on :class:`Protocol` instances:
429
430.. method:: Protocol.data_received(data)
431
432 Called when some data is received. *data* is a non-empty bytes object
433 containing the incoming data.
434
435 .. note::
436 Whether the data is buffered, chunked or reassembled depends on
437 the transport. In general, you shouldn't rely on specific semantics
438 and instead make your parsing generic and flexible enough. However,
439 data is always received in the correct order.
440
441.. method:: Protocol.eof_received()
442
443 Calls when the other end signals it won't send any more data
444 (for example by calling :meth:`write_eof`, if the other end also uses
445 asyncio).
446
447 This method may return a false value (including None), in which case
448 the transport will close itself. Conversely, if this method returns a
449 true value, closing the transport is up to the protocol. Since the
450 default implementation returns None, it implicitly closes the connection.
451
452 .. note::
453 Some transports such as SSL don't support half-closed connections,
454 in which case returning true from this method will not prevent closing
455 the connection.
456
457:meth:`data_received` can be called an arbitrary number of times during
458a connection. However, :meth:`eof_received` is called at most once
459and, if called, :meth:`data_received` won't be called after it.
460
461Datagram protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100462------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100463
464The following callbacks are called on :class:`DatagramProtocol` instances.
465
466.. method:: DatagramProtocol.datagram_received(data, addr)
467
468 Called when a datagram is received. *data* is a bytes object containing
469 the incoming data. *addr* is the address of the peer sending the data;
470 the exact format depends on the transport.
471
472.. method:: DatagramProtocol.error_received(exc)
473
474 Called when a previous send or receive operation raises an
475 :class:`OSError`. *exc* is the :class:`OSError` instance.
476
477 This method is called in rare conditions, when the transport (e.g. UDP)
478 detects that a datagram couldn't be delivered to its recipient.
479 In many conditions though, undeliverable datagrams will be silently
480 dropped.
481
482
483Flow control callbacks
484----------------------
485
486These callbacks may be called on :class:`Protocol` and
487:class:`SubprocessProtocol` instances:
488
489.. method:: BaseProtocol.pause_writing()
490
491 Called when the transport's buffer goes over the high-water mark.
492
493.. method:: BaseProtocol.resume_writing()
494
495 Called when the transport's buffer drains below the low-water mark.
496
497
498:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
499:meth:`pause_writing` is called once when the buffer goes strictly over
500the high-water mark (even if subsequent writes increases the buffer size
501even more), and eventually :meth:`resume_writing` is called once when the
502buffer size reaches the low-water mark.
503
504.. note::
505 If the buffer size equals the high-water mark,
506 :meth:`pause_writing` is not called -- it must go strictly over.
507 Conversely, :meth:`resume_writing` is called when the buffer size is
508 equal or lower than the low-water mark. These end conditions
509 are important to ensure that things go as expected when either
510 mark is zero.
511
512
513Server
514------
515
516.. class:: AbstractServer
517
518 Abstract server returned by create_service().
519
520 .. method:: close()
521
522 Stop serving. This leaves existing connections open.
523
524 .. method:: wait_closed()
525
526 Coroutine to wait until service is closed.
527
528
529Network functions
530=================
531
532.. function:: open_connection(host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds)
533
534 A wrapper for create_connection() returning a (reader, writer) pair.
535
536 The reader returned is a StreamReader instance; the writer is a
537 :class:`Transport`.
538
539 The arguments are all the usual arguments to
540 :meth:`BaseEventLoop.create_connection` except *protocol_factory*; most
541 common are positional host and port, with various optional keyword arguments
542 following.
543
544 Additional optional keyword arguments are *loop* (to set the event loop
545 instance to use) and *limit* (to set the buffer limit passed to the
546 StreamReader).
547
548 (If you want to customize the :class:`StreamReader` and/or
549 :class:`StreamReaderProtocol` classes, just copy the code -- there's really
550 nothing special here except some convenience.)
551
552 This function returns a :ref:`coroutine <coroutine>`.
553
554.. function:: start_server(client_connected_cb, host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds)
555
556 Start a socket server, call back for each client connected.
557
558 The first parameter, *client_connected_cb*, takes two parameters:
559 *client_reader*, *client_writer*. *client_reader* is a
560 :class:`StreamReader` object, while *client_writer* is a
561 :class:`StreamWriter` object. This parameter can either be a plain callback
562 function or a :ref:`coroutine <coroutine>`; if it is a coroutine, it will be
563 automatically converted into a :class:`Task`.
564
565 The rest of the arguments are all the usual arguments to
566 :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most
567 common are positional host and port, with various optional keyword arguments
568 following. The return value is the same as
569 :meth:`~BaseEventLoop.create_server()`.
570
571 Additional optional keyword arguments are *loop* (to set the event loop
572 instance to use) and *limit* (to set the buffer limit passed to the
573 :class:`StreamReader`).
574
575 The return value is the same as :meth:`~BaseEventLoop.create_server()`, i.e.
576 a :class:`AbstractServer` object which can be used to stop the service.
577
578 This function returns a :ref:`coroutine <coroutine>`.
579
Victor Stinnerea3183f2013-12-03 01:08:00 +0100580
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100581Protocol example: TCP echo client and server
582============================================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100583
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100584Echo server
585-----------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100586
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100587TCP echo server example::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100588
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100589 import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +0100590
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100591 class EchoServer(asyncio.Protocol):
592 def timeout(self):
593 print('connection timeout, closing.')
594 self.transport.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100595
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100596 def connection_made(self, transport):
597 print('connection made')
598 self.transport = transport
Victor Stinnerea3183f2013-12-03 01:08:00 +0100599
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100600 # close the client connection after 2 seconds
601 asyncio.get_event_loop().call_later(2.0, self.timeout)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100602
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100603 def data_received(self, data):
604 print('data received:', data.decode())
605 self.transport.write(data)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100606
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100607 def connection_lost(self, exc):
608 print('connection lost')
Victor Stinnerea3183f2013-12-03 01:08:00 +0100609
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100610
611 loop = asyncio.get_event_loop()
612 f = loop.create_server(EchoServer, '127.0.0.1', 8888)
613 s = loop.run_until_complete(f)
614 print('serving on', s.sockets[0].getsockname())
615 loop.run_forever()
616
617
618Echo client
619-----------
620
621TCP echo client example::
622
623 import asyncio
624
625 class EchoClient(asyncio.Protocol):
626 message = 'This is the message. It will be echoed.'
627
628 def connection_made(self, transport):
629 self.transport = transport
630 self.transport.write(self.message.encode())
631 print('data sent:', self.message)
632
633 def data_received(self, data):
634 print('data received:', data.decode())
635
636 def connection_lost(self, exc):
637 print('connection lost')
638 asyncio.get_event_loop().stop()
639
640 loop = asyncio.get_event_loop()
641 task = loop.create_connection(EchoClient, '127.0.0.1', 8888)
642 loop.run_until_complete(task)
643 loop.run_forever()
644 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100645