blob: 656816f75b020cfa752f280c7b63b4df5aba0d5e [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
Victor Stinner83704962015-02-25 14:24:15 +010026The transport classes are :ref:`not thread safe <asyncio-multithreading>`.
27
Victor Stinnerea3183f2013-12-03 01:08:00 +010028
Victor Stinner0c6f1ca2013-12-03 01:46:39 +010029BaseTransport
30-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
32.. class:: BaseTransport
33
34 Base class for transports.
35
36 .. method:: close(self)
37
38 Close the transport. If the transport has a buffer for outgoing
39 data, buffered data will be flushed asynchronously. No more data
40 will be received. After all buffered data is flushed, the
41 protocol's :meth:`connection_lost` method will be called with
42 :const:`None` as its argument.
43
44
45 .. method:: get_extra_info(name, default=None)
46
47 Return optional transport information. *name* is a string representing
48 the piece of transport-specific information to get, *default* is the
49 value to return if the information doesn't exist.
50
51 This method allows transport implementations to easily expose
52 channel-specific information.
53
54 * socket:
55
56 - ``'peername'``: the remote address to which the socket is connected,
57 result of :meth:`socket.socket.getpeername` (``None`` on error)
58 - ``'socket'``: :class:`socket.socket` instance
59 - ``'sockname'``: the socket's own address,
60 result of :meth:`socket.socket.getsockname`
61
62 * SSL socket:
63
64 - ``'compression'``: the compression algorithm being used as a string,
65 or ``None`` if the connection isn't compressed; result of
66 :meth:`ssl.SSLSocket.compression`
67 - ``'cipher'``: a three-value tuple containing the name of the cipher
68 being used, the version of the SSL protocol that defines its use, and
69 the number of secret bits being used; result of
70 :meth:`ssl.SSLSocket.cipher`
71 - ``'peercert'``: peer certificate; result of
72 :meth:`ssl.SSLSocket.getpeercert`
73 - ``'sslcontext'``: :class:`ssl.SSLContext` instance
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +020074 - ``'ssl_object'``: :class:`ssl.SSLObject` or :class:`ssl.SSLSocket`
75 instance
Victor Stinnerea3183f2013-12-03 01:08:00 +010076
77 * pipe:
78
79 - ``'pipe'``: pipe object
80
81 * subprocess:
82
83 - ``'subprocess'``: :class:`subprocess.Popen` instance
84
Victor Stinnerf7dc7fb2015-09-21 18:06:17 +020085 .. versionchanged:: 3.4.4
86 ``'ssl_object'`` info was added to SSL sockets.
87
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
Victor Stinner0c6f1ca2013-12-03 01:46:39 +010089ReadTransport
90-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010091
92.. class:: ReadTransport
93
94 Interface for read-only transports.
95
96 .. method:: pause_reading()
97
98 Pause the receiving end of the transport. No data will be passed to
Victor Stinner51f31292014-03-21 17:17:15 +010099 the protocol's :meth:`data_received` method until :meth:`resume_reading`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100100 is called.
101
102 .. method:: resume_reading()
103
104 Resume the receiving end. The protocol's :meth:`data_received` method
105 will be called once again if some data is available for reading.
106
107
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100108WriteTransport
109--------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100110
111.. class:: WriteTransport
112
113 Interface for write-only transports.
114
115 .. method:: abort()
116
117 Close the transport immediately, without waiting for pending operations
118 to complete. Buffered data will be lost. No more data will be received.
119 The protocol's :meth:`connection_lost` method will eventually be
120 called with :const:`None` as its argument.
121
122 .. method:: can_write_eof()
123
124 Return :const:`True` if the transport supports :meth:`write_eof`,
125 :const:`False` if not.
126
127 .. method:: get_write_buffer_size()
128
129 Return the current size of the output buffer used by the transport.
130
Victor Stinner52bb9492014-08-26 00:22:28 +0200131 .. method:: get_write_buffer_limits()
132
133 Get the *high*- and *low*-water limits for write flow control. Return a
134 tuple ``(low, high)`` where *low* and *high* are positive number of
135 bytes.
136
137 Use :meth:`set_write_buffer_limits` to set the limits.
138
139 .. versionadded:: 3.4.2
140
Victor Stinnerea3183f2013-12-03 01:08:00 +0100141 .. method:: set_write_buffer_limits(high=None, low=None)
142
143 Set the *high*- and *low*-water limits for write flow control.
144
145 These two values control when call the protocol's
146 :meth:`pause_writing` and :meth:`resume_writing` methods are called.
147 If specified, the low-water limit must be less than or equal to the
148 high-water limit. Neither *high* nor *low* can be negative.
149
150 The defaults are implementation-specific. If only the
151 high-water limit is given, the low-water limit defaults to a
152 implementation-specific value less than or equal to the
153 high-water limit. Setting *high* to zero forces *low* to zero as
154 well, and causes :meth:`pause_writing` to be called whenever the
155 buffer becomes non-empty. Setting *low* to zero causes
156 :meth:`resume_writing` to be called only once the buffer is empty.
157 Use of zero for either limit is generally sub-optimal as it
158 reduces opportunities for doing I/O and computation
159 concurrently.
160
Victor Stinner52bb9492014-08-26 00:22:28 +0200161 Use :meth:`get_write_buffer_limits` to get the limits.
162
Victor Stinnerea3183f2013-12-03 01:08:00 +0100163 .. method:: write(data)
164
165 Write some *data* bytes to the transport.
166
167 This method does not block; it buffers the data and arranges for it
168 to be sent out asynchronously.
169
170 .. method:: writelines(list_of_data)
171
172 Write a list (or any iterable) of data bytes to the transport.
173 This is functionally equivalent to calling :meth:`write` on each
174 element yielded by the iterable, but may be implemented more efficiently.
175
176 .. method:: write_eof()
177
178 Close the write end of the transport after flushing buffered data.
179 Data may still be received.
180
181 This method can raise :exc:`NotImplementedError` if the transport
182 (e.g. SSL) doesn't support half-closes.
183
184
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100185DatagramTransport
186-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100187
188.. method:: DatagramTransport.sendto(data, addr=None)
189
190 Send the *data* bytes to the remote peer given by *addr* (a
191 transport-dependent target address). If *addr* is :const:`None`, the
192 data is sent to the target address given on transport creation.
193
194 This method does not block; it buffers the data and arranges for it
195 to be sent out asynchronously.
196
197.. method:: DatagramTransport.abort()
198
199 Close the transport immediately, without waiting for pending operations
200 to complete. Buffered data will be lost. No more data will be received.
201 The protocol's :meth:`connection_lost` method will eventually be
202 called with :const:`None` as its argument.
203
204
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100205BaseSubprocessTransport
206-----------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100207
208.. class:: BaseSubprocessTransport
209
210 .. method:: get_pid()
211
212 Return the subprocess process id as an integer.
213
Victor Stinnerea3183f2013-12-03 01:08:00 +0100214 .. method:: get_pipe_transport(fd)
215
Brian Curtina1afeec2014-02-08 18:36:14 -0600216 Return the transport for the communication pipe corresponding to the
Victor Stinner4270a242014-10-13 23:56:43 +0200217 integer file descriptor *fd*:
218
219 * ``0``: readable streaming transport of the standard input (*stdin*),
220 or :const:`None` if the subprocess was not created with ``stdin=PIPE``
221 * ``1``: writable streaming transport of the standard output (*stdout*),
222 or :const:`None` if the subprocess was not created with ``stdout=PIPE``
223 * ``2``: writable streaming transport of the standard error (*stderr*),
224 or :const:`None` if the subprocess was not created with ``stderr=PIPE``
225 * other *fd*: :const:`None`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100226
Victor Stinner933a8c82013-12-03 01:59:38 +0100227 .. method:: get_returncode()
228
229 Return the subprocess returncode as an integer or :const:`None`
230 if it hasn't returned, similarly to the
231 :attr:`subprocess.Popen.returncode` attribute.
232
233 .. method:: kill(self)
234
235 Kill the subprocess, as in :meth:`subprocess.Popen.kill`
236
237 On POSIX systems, the function sends SIGKILL to the subprocess.
238 On Windows, this method is an alias for :meth:`terminate`.
239
Victor Stinnerea3183f2013-12-03 01:08:00 +0100240 .. method:: send_signal(signal)
241
242 Send the *signal* number to the subprocess, as in
243 :meth:`subprocess.Popen.send_signal`.
244
245 .. method:: terminate()
246
247 Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`.
248 This method is an alias for the :meth:`close` method.
249
250 On POSIX systems, this method sends SIGTERM to the subprocess.
251 On Windows, the Windows API function TerminateProcess() is called to
252 stop the subprocess.
253
Victor Stinner4270a242014-10-13 23:56:43 +0200254 .. method:: close()
255
256 Ask the subprocess to stop by calling the :meth:`terminate` method if the
257 subprocess hasn't returned yet, and close transports of all pipes
258 (*stdin*, *stdout* and *stderr*).
259
Victor Stinnerea3183f2013-12-03 01:08:00 +0100260
Victor Stinner9592edb2014-02-02 15:03:02 +0100261.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100262
263Protocols
264=========
265
266:mod:`asyncio` provides base classes that you can subclass to implement
267your network protocols. Those classes are used in conjunction with
Victor Stinner9592edb2014-02-02 15:03:02 +0100268:ref:`transports <asyncio-transport>` (see below): the protocol parses incoming
Victor Stinnerea3183f2013-12-03 01:08:00 +0100269data and asks for the writing of outgoing data, while the transport is
270responsible for the actual I/O and buffering.
271
272When subclassing a protocol class, it is recommended you override certain
273methods. Those methods are callbacks: they will be called by the transport
274on certain events (for example when some data is received); you shouldn't
275call them yourself, unless you are implementing a transport.
276
277.. note::
278 All callbacks have default implementations, which are empty. Therefore,
279 you only need to implement the callbacks for the events in which you
280 are interested.
281
282
283Protocol classes
284----------------
285
286.. class:: Protocol
287
288 The base class for implementing streaming protocols (for use with
289 e.g. TCP and SSL transports).
290
291.. class:: DatagramProtocol
292
293 The base class for implementing datagram protocols (for use with
294 e.g. UDP transports).
295
296.. class:: SubprocessProtocol
297
298 The base class for implementing protocols communicating with child
299 processes (through a set of unidirectional pipes).
300
301
302Connection callbacks
303--------------------
304
Victor Stinner15386652014-06-10 09:19:26 +0200305These callbacks may be called on :class:`Protocol`, :class:`DatagramProtocol`
306and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100307
308.. method:: BaseProtocol.connection_made(transport)
309
310 Called when a connection is made.
311
312 The *transport* argument is the transport representing the
313 connection. You are responsible for storing it somewhere
314 (e.g. as an attribute) if you need to.
315
316.. method:: BaseProtocol.connection_lost(exc)
317
318 Called when the connection is lost or closed.
319
320 The argument is either an exception object or :const:`None`.
321 The latter means a regular EOF is received, or the connection was
322 aborted or closed by this side of the connection.
323
Victor Stinner15386652014-06-10 09:19:26 +0200324:meth:`~BaseProtocol.connection_made` and :meth:`~BaseProtocol.connection_lost`
325are called exactly once per successful connection. All other callbacks will be
326called between those two methods, which allows for easier resource management
327in your protocol implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100328
329The following callbacks may be called only on :class:`SubprocessProtocol`
330instances:
331
332.. method:: SubprocessProtocol.pipe_data_received(fd, data)
333
334 Called when the child process writes data into its stdout or stderr pipe.
335 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
336 bytes object containing the data.
337
338.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
339
340 Called when one of the pipes communicating with the child process
341 is closed. *fd* is the integer file descriptor that was closed.
342
343.. method:: SubprocessProtocol.process_exited()
344
345 Called when the child process has exited.
346
347
Victor Stinnerea3183f2013-12-03 01:08:00 +0100348Streaming protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100349-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100350
351The following callbacks are called on :class:`Protocol` instances:
352
353.. method:: Protocol.data_received(data)
354
355 Called when some data is received. *data* is a non-empty bytes object
356 containing the incoming data.
357
358 .. note::
359 Whether the data is buffered, chunked or reassembled depends on
360 the transport. In general, you shouldn't rely on specific semantics
361 and instead make your parsing generic and flexible enough. However,
362 data is always received in the correct order.
363
364.. method:: Protocol.eof_received()
365
366 Calls when the other end signals it won't send any more data
367 (for example by calling :meth:`write_eof`, if the other end also uses
368 asyncio).
369
370 This method may return a false value (including None), in which case
371 the transport will close itself. Conversely, if this method returns a
372 true value, closing the transport is up to the protocol. Since the
373 default implementation returns None, it implicitly closes the connection.
374
375 .. note::
376 Some transports such as SSL don't support half-closed connections,
377 in which case returning true from this method will not prevent closing
378 the connection.
379
380:meth:`data_received` can be called an arbitrary number of times during
381a connection. However, :meth:`eof_received` is called at most once
382and, if called, :meth:`data_received` won't be called after it.
383
Victor Stinner54a231d2015-01-29 13:33:15 +0100384State machine:
385
386 start -> :meth:`~BaseProtocol.connection_made`
387 [-> :meth:`~Protocol.data_received` \*]
388 [-> :meth:`~Protocol.eof_received` ?]
389 -> :meth:`~BaseProtocol.connection_lost` -> end
390
391
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392Datagram protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100393------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100394
395The following callbacks are called on :class:`DatagramProtocol` instances.
396
397.. method:: DatagramProtocol.datagram_received(data, addr)
398
399 Called when a datagram is received. *data* is a bytes object containing
400 the incoming data. *addr* is the address of the peer sending the data;
401 the exact format depends on the transport.
402
403.. method:: DatagramProtocol.error_received(exc)
404
405 Called when a previous send or receive operation raises an
406 :class:`OSError`. *exc* is the :class:`OSError` instance.
407
408 This method is called in rare conditions, when the transport (e.g. UDP)
409 detects that a datagram couldn't be delivered to its recipient.
410 In many conditions though, undeliverable datagrams will be silently
411 dropped.
412
413
414Flow control callbacks
415----------------------
416
Larry Hastings3732ed22014-03-15 21:13:56 -0700417These callbacks may be called on :class:`Protocol`,
418:class:`DatagramProtocol` and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100419
420.. method:: BaseProtocol.pause_writing()
421
422 Called when the transport's buffer goes over the high-water mark.
423
424.. method:: BaseProtocol.resume_writing()
425
426 Called when the transport's buffer drains below the low-water mark.
427
428
429:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
430:meth:`pause_writing` is called once when the buffer goes strictly over
431the high-water mark (even if subsequent writes increases the buffer size
432even more), and eventually :meth:`resume_writing` is called once when the
433buffer size reaches the low-water mark.
434
435.. note::
436 If the buffer size equals the high-water mark,
437 :meth:`pause_writing` is not called -- it must go strictly over.
438 Conversely, :meth:`resume_writing` is called when the buffer size is
439 equal or lower than the low-water mark. These end conditions
440 are important to ensure that things go as expected when either
441 mark is zero.
442
Larry Hastings3732ed22014-03-15 21:13:56 -0700443.. note::
444 On BSD systems (OS X, FreeBSD, etc.) flow control is not supported
445 for :class:`DatagramProtocol`, because send failures caused by
446 writing too many packets cannot be detected easily. The socket
447 always appears 'ready' and excess packets are dropped; an
448 :class:`OSError` with errno set to :const:`errno.ENOBUFS` may or
449 may not be raised; if it is raised, it will be reported to
450 :meth:`DatagramProtocol.error_received` but otherwise ignored.
451
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100453Coroutines and protocols
454------------------------
455
456Coroutines can be scheduled in a protocol method using :func:`async`, but there
R David Murray64f10d42014-11-02 12:32:26 -0500457is no guarantee made about the execution order. Protocols are not aware of
458coroutines created in protocol methods and so will not wait for them.
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100459
Victor Stinner9592edb2014-02-02 15:03:02 +0100460To have a reliable execution order, use :ref:`stream objects <asyncio-streams>` in a
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100461coroutine with ``yield from``. For example, the :meth:`StreamWriter.drain`
462coroutine can be used to wait until the write buffer is flushed.
463
464
Victor Stinner04e6df32014-10-11 16:16:27 +0200465Protocol examples
466=================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100467
Victor Stinnered051592014-10-12 20:18:16 +0200468.. _asyncio-tcp-echo-client-protocol:
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100469
Victor Stinnered051592014-10-12 20:18:16 +0200470TCP echo client protocol
471------------------------
472
473TCP echo client using the :meth:`BaseEventLoop.create_connection` method, send
474data and wait until the connection is closed::
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100475
476 import asyncio
477
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200478 class EchoClientProtocol(asyncio.Protocol):
Victor Stinner53664342014-10-12 11:35:09 +0200479 def __init__(self, message, loop):
480 self.message = message
481 self.loop = loop
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100482
483 def connection_made(self, transport):
Victor Stinner31d83222013-12-04 11:16:17 +0100484 transport.write(self.message.encode())
Victor Stinner53664342014-10-12 11:35:09 +0200485 print('Data sent: {!r}'.format(self.message))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100486
487 def data_received(self, data):
Victor Stinner53664342014-10-12 11:35:09 +0200488 print('Data received: {!r}'.format(data.decode()))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100489
490 def connection_lost(self, exc):
Victor Stinner53664342014-10-12 11:35:09 +0200491 print('The server closed the connection')
492 print('Stop the event lop')
493 self.loop.stop()
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100494
495 loop = asyncio.get_event_loop()
Victor Stinner53664342014-10-12 11:35:09 +0200496 message = 'Hello World!'
497 coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
498 '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100499 loop.run_until_complete(coro)
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100500 loop.run_forever()
501 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100502
Victor Stinnera881a7f2013-12-09 13:19:23 +0100503The event loop is running twice. The
504:meth:`~BaseEventLoop.run_until_complete` method is preferred in this short
505example to raise an exception if the server is not listening, instead of
506having to write a short coroutine to handle the exception and stop the
507running loop. At :meth:`~BaseEventLoop.run_until_complete` exit, the loop is
Andrew Svetlov588517c2014-07-23 11:27:17 +0300508no longer running, so there is no need to stop the loop in case of an error.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100509
Victor Stinnered051592014-10-12 20:18:16 +0200510.. seealso::
Victor Stinnerc2721b42014-10-12 11:13:40 +0200511
Victor Stinnered051592014-10-12 20:18:16 +0200512 The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
513 example uses the :func:`asyncio.open_connection` function.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100514
Victor Stinnered051592014-10-12 20:18:16 +0200515
516.. _asyncio-tcp-echo-server-protocol:
517
518TCP echo server protocol
519------------------------
520
521TCP echo server using the :meth:`BaseEventLoop.create_server` method, send back
522received data and close the connection::
Victor Stinnera881a7f2013-12-09 13:19:23 +0100523
524 import asyncio
525
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200526 class EchoServerClientProtocol(asyncio.Protocol):
Victor Stinnera881a7f2013-12-09 13:19:23 +0100527 def connection_made(self, transport):
528 peername = transport.get_extra_info('peername')
Victor Stinnerc2721b42014-10-12 11:13:40 +0200529 print('Connection from {}'.format(peername))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100530 self.transport = transport
531
532 def data_received(self, data):
Victor Stinnerc2721b42014-10-12 11:13:40 +0200533 message = data.decode()
534 print('Data received: {!r}'.format(message))
535
536 print('Send: {!r}'.format(message))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100537 self.transport.write(data)
538
Victor Stinner53664342014-10-12 11:35:09 +0200539 print('Close the client socket')
Victor Stinnera881a7f2013-12-09 13:19:23 +0100540 self.transport.close()
541
542 loop = asyncio.get_event_loop()
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200543 # Each client connection will create a new protocol instance
544 coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100545 server = loop.run_until_complete(coro)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100546
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300547 # Serve requests until Ctrl+C is pressed
Victor Stinnerc2721b42014-10-12 11:13:40 +0200548 print('Serving on {}'.format(server.sockets[0].getsockname()))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100549 try:
550 loop.run_forever()
551 except KeyboardInterrupt:
Victor Stinnered051592014-10-12 20:18:16 +0200552 pass
Victor Stinnerc2721b42014-10-12 11:13:40 +0200553
554 # Close the server
555 server.close()
556 loop.run_until_complete(server.wait_closed())
557 loop.close()
Victor Stinnera881a7f2013-12-09 13:19:23 +0100558
R David Murray530a69f2013-12-14 11:26:06 -0500559:meth:`Transport.close` can be called immediately after
Victor Stinnera881a7f2013-12-09 13:19:23 +0100560:meth:`WriteTransport.write` even if data are not sent yet on the socket: both
561methods are asynchronous. ``yield from`` is not needed because these transport
Larry Hastings3732ed22014-03-15 21:13:56 -0700562methods are not coroutines.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100563
Victor Stinnered051592014-10-12 20:18:16 +0200564.. seealso::
565
566 The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>`
567 example uses the :func:`asyncio.start_server` function.
568
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200569
570.. _asyncio-udp-echo-client-protocol:
571
572UDP echo client protocol
573------------------------
574
575UDP echo client using the :meth:`BaseEventLoop.create_datagram_endpoint`
576method, send data and close the transport when we received the answer::
577
578 import asyncio
579
580 class EchoClientProtocol:
581 def __init__(self, message, loop):
582 self.message = message
583 self.loop = loop
584 self.transport = None
585
586 def connection_made(self, transport):
587 self.transport = transport
588 print('Send:', self.message)
589 self.transport.sendto(self.message.encode())
590
591 def datagram_received(self, data, addr):
592 print("Received:", data.decode())
593
594 print("Close the socket")
595 self.transport.close()
596
597 def error_received(self, exc):
598 print('Error received:', exc)
599
600 def connection_lost(self, exc):
601 print("Socket closed, stop the event loop")
602 loop = asyncio.get_event_loop()
603 loop.stop()
604
605 loop = asyncio.get_event_loop()
606 message = "Hello World!"
607 connect = loop.create_datagram_endpoint(
608 lambda: EchoClientProtocol(message, loop),
609 remote_addr=('127.0.0.1', 9999))
610 transport, protocol = loop.run_until_complete(connect)
611 loop.run_forever()
612 transport.close()
613 loop.close()
614
615
616.. _asyncio-udp-echo-server-protocol:
617
618UDP echo server protocol
619------------------------
620
621UDP echo server using the :meth:`BaseEventLoop.create_datagram_endpoint`
622method, send back received data::
623
624 import asyncio
625
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200626 class EchoServerProtocol:
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200627 def connection_made(self, transport):
628 self.transport = transport
629
630 def datagram_received(self, data, addr):
631 message = data.decode()
632 print('Received %r from %s' % (message, addr))
633 print('Send %r to %s' % (message, addr))
634 self.transport.sendto(data, addr)
635
636 loop = asyncio.get_event_loop()
637 print("Starting UDP server")
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200638 # One protocol instance will be created to serve all client requests
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200639 listen = loop.create_datagram_endpoint(
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200640 EchoServerProtocol, local_addr=('127.0.0.1', 9999))
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200641 transport, protocol = loop.run_until_complete(listen)
642
643 try:
644 loop.run_forever()
645 except KeyboardInterrupt:
646 pass
647
648 transport.close()
649 loop.close()
650
651
Victor Stinner04e6df32014-10-11 16:16:27 +0200652.. _asyncio-register-socket:
Victor Stinnera881a7f2013-12-09 13:19:23 +0100653
Victor Stinner04e6df32014-10-11 16:16:27 +0200654Register an open socket to wait for data using a protocol
655---------------------------------------------------------
656
657Wait until a socket receives data using the
658:meth:`BaseEventLoop.create_connection` method with a protocol, and then close
659the event loop ::
660
661 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200662 try:
663 from socket import socketpair
664 except ImportError:
665 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200666
667 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200668 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200669 loop = asyncio.get_event_loop()
670
671 class MyProtocol(asyncio.Protocol):
672 transport = None
673
674 def connection_made(self, transport):
675 self.transport = transport
676
677 def data_received(self, data):
678 print("Received:", data.decode())
679
680 # We are done: close the transport (it will call connection_lost())
681 self.transport.close()
682
683 def connection_lost(self, exc):
684 # The socket has been closed, stop the event loop
685 loop.stop()
686
687 # Register the socket to wait for data
688 connect_coro = loop.create_connection(MyProtocol, sock=rsock)
689 transport, protocol = loop.run_until_complete(connect_coro)
690
691 # Simulate the reception of data from the network
692 loop.call_soon(wsock.send, 'abc'.encode())
693
694 # Run the event loop
695 loop.run_forever()
696
697 # We are done, close sockets and the event loop
698 rsock.close()
699 wsock.close()
700 loop.close()
701
702.. seealso::
703
704 The :ref:`watch a file descriptor for read events
705 <asyncio-watch-read-event>` example uses the low-level
706 :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a
707 socket.
708
709 The :ref:`register an open socket to wait for data using streams
710 <asyncio-register-socket-streams>` example uses high-level streams
711 created by the :func:`open_connection` function in a coroutine.