blob: 952ab690f2f8276a088dd0b0ce2a8e31beaef330 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Victor Stinner1374bd42014-01-24 15:34:19 +01003+++++++++++++++++++++++++++++++++++++++++
4Transports and protocols (low-level API)
5+++++++++++++++++++++++++++++++++++++++++
Victor Stinner1ca5ba62013-12-03 01:49:43 +01006
Victor Stinner9592edb2014-02-02 15:03:02 +01007.. _asyncio-transport:
Victor Stinnerea3183f2013-12-03 01:08:00 +01008
9Transports
10==========
11
Guido van Rossum589872c2014-03-29 21:14:04 -070012Transports are classes provided by :mod:`asyncio` in order to abstract
Victor Stinnerea3183f2013-12-03 01:08:00 +010013various 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
Victor Stinner9592edb2014-02-02 15:03:02 +010019paired with a :ref:`protocol <asyncio-protocol>` instance. The protocol can
Victor Stinnerea3183f2013-12-03 01:08:00 +010020then 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
Victor Stinner51f31292014-03-21 17:17:15 +010092 the protocol's :meth:`data_received` method until :meth:`resume_reading`
Victor Stinnerea3183f2013-12-03 01:08:00 +010093 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
Brian Curtina1afeec2014-02-08 18:36:14 -0600197 Return the transport for the communication pipe corresponding to the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100198 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 Stinner9592edb2014-02-02 15:03:02 +0100231.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100232
233Protocols
234=========
235
236:mod:`asyncio` provides base classes that you can subclass to implement
237your network protocols. Those classes are used in conjunction with
Victor Stinner9592edb2014-02-02 15:03:02 +0100238:ref:`transports <asyncio-transport>` (see below): the protocol parses incoming
Victor Stinnerea3183f2013-12-03 01:08:00 +0100239data and asks for the writing of outgoing data, while the transport is
240responsible for the actual I/O and buffering.
241
242When subclassing a protocol class, it is recommended you override certain
243methods. Those methods are callbacks: they will be called by the transport
244on certain events (for example when some data is received); you shouldn't
245call them yourself, unless you are implementing a transport.
246
247.. note::
248 All callbacks have default implementations, which are empty. Therefore,
249 you only need to implement the callbacks for the events in which you
250 are interested.
251
252
253Protocol classes
254----------------
255
256.. class:: Protocol
257
258 The base class for implementing streaming protocols (for use with
259 e.g. TCP and SSL transports).
260
261.. class:: DatagramProtocol
262
263 The base class for implementing datagram protocols (for use with
264 e.g. UDP transports).
265
266.. class:: SubprocessProtocol
267
268 The base class for implementing protocols communicating with child
269 processes (through a set of unidirectional pipes).
270
271
272Connection callbacks
273--------------------
274
Victor Stinner15386652014-06-10 09:19:26 +0200275These callbacks may be called on :class:`Protocol`, :class:`DatagramProtocol`
276and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277
278.. method:: BaseProtocol.connection_made(transport)
279
280 Called when a connection is made.
281
282 The *transport* argument is the transport representing the
283 connection. You are responsible for storing it somewhere
284 (e.g. as an attribute) if you need to.
285
286.. method:: BaseProtocol.connection_lost(exc)
287
288 Called when the connection is lost or closed.
289
290 The argument is either an exception object or :const:`None`.
291 The latter means a regular EOF is received, or the connection was
292 aborted or closed by this side of the connection.
293
Victor Stinner15386652014-06-10 09:19:26 +0200294:meth:`~BaseProtocol.connection_made` and :meth:`~BaseProtocol.connection_lost`
295are called exactly once per successful connection. All other callbacks will be
296called between those two methods, which allows for easier resource management
297in your protocol implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100298
299The following callbacks may be called only on :class:`SubprocessProtocol`
300instances:
301
302.. method:: SubprocessProtocol.pipe_data_received(fd, data)
303
304 Called when the child process writes data into its stdout or stderr pipe.
305 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
306 bytes object containing the data.
307
308.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
309
310 Called when one of the pipes communicating with the child process
311 is closed. *fd* is the integer file descriptor that was closed.
312
313.. method:: SubprocessProtocol.process_exited()
314
315 Called when the child process has exited.
316
317
Victor Stinnerea3183f2013-12-03 01:08:00 +0100318Streaming protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100319-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100320
321The following callbacks are called on :class:`Protocol` instances:
322
323.. method:: Protocol.data_received(data)
324
325 Called when some data is received. *data* is a non-empty bytes object
326 containing the incoming data.
327
328 .. note::
329 Whether the data is buffered, chunked or reassembled depends on
330 the transport. In general, you shouldn't rely on specific semantics
331 and instead make your parsing generic and flexible enough. However,
332 data is always received in the correct order.
333
334.. method:: Protocol.eof_received()
335
336 Calls when the other end signals it won't send any more data
337 (for example by calling :meth:`write_eof`, if the other end also uses
338 asyncio).
339
340 This method may return a false value (including None), in which case
341 the transport will close itself. Conversely, if this method returns a
342 true value, closing the transport is up to the protocol. Since the
343 default implementation returns None, it implicitly closes the connection.
344
345 .. note::
346 Some transports such as SSL don't support half-closed connections,
347 in which case returning true from this method will not prevent closing
348 the connection.
349
350:meth:`data_received` can be called an arbitrary number of times during
351a connection. However, :meth:`eof_received` is called at most once
352and, if called, :meth:`data_received` won't be called after it.
353
354Datagram protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100355------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
357The following callbacks are called on :class:`DatagramProtocol` instances.
358
359.. method:: DatagramProtocol.datagram_received(data, addr)
360
361 Called when a datagram is received. *data* is a bytes object containing
362 the incoming data. *addr* is the address of the peer sending the data;
363 the exact format depends on the transport.
364
365.. method:: DatagramProtocol.error_received(exc)
366
367 Called when a previous send or receive operation raises an
368 :class:`OSError`. *exc* is the :class:`OSError` instance.
369
370 This method is called in rare conditions, when the transport (e.g. UDP)
371 detects that a datagram couldn't be delivered to its recipient.
372 In many conditions though, undeliverable datagrams will be silently
373 dropped.
374
375
376Flow control callbacks
377----------------------
378
Larry Hastings3732ed22014-03-15 21:13:56 -0700379These callbacks may be called on :class:`Protocol`,
380:class:`DatagramProtocol` and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100381
382.. method:: BaseProtocol.pause_writing()
383
384 Called when the transport's buffer goes over the high-water mark.
385
386.. method:: BaseProtocol.resume_writing()
387
388 Called when the transport's buffer drains below the low-water mark.
389
390
391:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
392:meth:`pause_writing` is called once when the buffer goes strictly over
393the high-water mark (even if subsequent writes increases the buffer size
394even more), and eventually :meth:`resume_writing` is called once when the
395buffer size reaches the low-water mark.
396
397.. note::
398 If the buffer size equals the high-water mark,
399 :meth:`pause_writing` is not called -- it must go strictly over.
400 Conversely, :meth:`resume_writing` is called when the buffer size is
401 equal or lower than the low-water mark. These end conditions
402 are important to ensure that things go as expected when either
403 mark is zero.
404
Larry Hastings3732ed22014-03-15 21:13:56 -0700405.. note::
406 On BSD systems (OS X, FreeBSD, etc.) flow control is not supported
407 for :class:`DatagramProtocol`, because send failures caused by
408 writing too many packets cannot be detected easily. The socket
409 always appears 'ready' and excess packets are dropped; an
410 :class:`OSError` with errno set to :const:`errno.ENOBUFS` may or
411 may not be raised; if it is raised, it will be reported to
412 :meth:`DatagramProtocol.error_received` but otherwise ignored.
413
Victor Stinnerea3183f2013-12-03 01:08:00 +0100414
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100415Coroutines and protocols
416------------------------
417
418Coroutines can be scheduled in a protocol method using :func:`async`, but there
419is not guarantee on the execution order. Protocols are not aware of coroutines
420created in protocol methods and so will not wait for them.
421
Victor Stinner9592edb2014-02-02 15:03:02 +0100422To have a reliable execution order, use :ref:`stream objects <asyncio-streams>` in a
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100423coroutine with ``yield from``. For example, the :meth:`StreamWriter.drain`
424coroutine can be used to wait until the write buffer is flushed.
425
426
Victor Stinner31d83222013-12-04 11:16:17 +0100427Protocol example: TCP echo server and client
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100428============================================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100429
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100430Echo client
431-----------
432
Victor Stinner31d83222013-12-04 11:16:17 +0100433TCP echo client example, send data and wait until the connection is closed::
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100434
435 import asyncio
436
437 class EchoClient(asyncio.Protocol):
438 message = 'This is the message. It will be echoed.'
439
440 def connection_made(self, transport):
Victor Stinner31d83222013-12-04 11:16:17 +0100441 transport.write(self.message.encode())
442 print('data sent: {}'.format(self.message))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100443
444 def data_received(self, data):
Victor Stinner31d83222013-12-04 11:16:17 +0100445 print('data received: {}'.format(data.decode()))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100446
447 def connection_lost(self, exc):
Victor Stinner31d83222013-12-04 11:16:17 +0100448 print('server closed the connection')
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100449 asyncio.get_event_loop().stop()
450
451 loop = asyncio.get_event_loop()
Victor Stinnera881a7f2013-12-09 13:19:23 +0100452 coro = loop.create_connection(EchoClient, '127.0.0.1', 8888)
453 loop.run_until_complete(coro)
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100454 loop.run_forever()
455 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100456
Victor Stinnera881a7f2013-12-09 13:19:23 +0100457The event loop is running twice. The
458:meth:`~BaseEventLoop.run_until_complete` method is preferred in this short
459example to raise an exception if the server is not listening, instead of
460having to write a short coroutine to handle the exception and stop the
461running loop. At :meth:`~BaseEventLoop.run_until_complete` exit, the loop is
Andrew Svetlov588517c2014-07-23 11:27:17 +0300462no longer running, so there is no need to stop the loop in case of an error.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100463
464Echo server
465-----------
466
467TCP echo server example, send back received data and close the connection::
468
469 import asyncio
470
471 class EchoServer(asyncio.Protocol):
472 def connection_made(self, transport):
473 peername = transport.get_extra_info('peername')
474 print('connection from {}'.format(peername))
475 self.transport = transport
476
477 def data_received(self, data):
478 print('data received: {}'.format(data.decode()))
479 self.transport.write(data)
480
481 # close the socket
482 self.transport.close()
483
484 loop = asyncio.get_event_loop()
485 coro = loop.create_server(EchoServer, '127.0.0.1', 8888)
486 server = loop.run_until_complete(coro)
487 print('serving on {}'.format(server.sockets[0].getsockname()))
488
489 try:
490 loop.run_forever()
491 except KeyboardInterrupt:
492 print("exit")
493 finally:
494 server.close()
495 loop.close()
496
R David Murray530a69f2013-12-14 11:26:06 -0500497:meth:`Transport.close` can be called immediately after
Victor Stinnera881a7f2013-12-09 13:19:23 +0100498:meth:`WriteTransport.write` even if data are not sent yet on the socket: both
499methods are asynchronous. ``yield from`` is not needed because these transport
Larry Hastings3732ed22014-03-15 21:13:56 -0700500methods are not coroutines.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100501
502