blob: 60776d1e9e30b87e67e6686e6814d16977eb65ea [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
Victor Stinner52bb9492014-08-26 00:22:28 +0200124 .. method:: get_write_buffer_limits()
125
126 Get the *high*- and *low*-water limits for write flow control. Return a
127 tuple ``(low, high)`` where *low* and *high* are positive number of
128 bytes.
129
130 Use :meth:`set_write_buffer_limits` to set the limits.
131
132 .. versionadded:: 3.4.2
133
Victor Stinnerea3183f2013-12-03 01:08:00 +0100134 .. method:: set_write_buffer_limits(high=None, low=None)
135
136 Set the *high*- and *low*-water limits for write flow control.
137
138 These two values control when call the protocol's
139 :meth:`pause_writing` and :meth:`resume_writing` methods are called.
140 If specified, the low-water limit must be less than or equal to the
141 high-water limit. Neither *high* nor *low* can be negative.
142
143 The defaults are implementation-specific. If only the
144 high-water limit is given, the low-water limit defaults to a
145 implementation-specific value less than or equal to the
146 high-water limit. Setting *high* to zero forces *low* to zero as
147 well, and causes :meth:`pause_writing` to be called whenever the
148 buffer becomes non-empty. Setting *low* to zero causes
149 :meth:`resume_writing` to be called only once the buffer is empty.
150 Use of zero for either limit is generally sub-optimal as it
151 reduces opportunities for doing I/O and computation
152 concurrently.
153
Victor Stinner52bb9492014-08-26 00:22:28 +0200154 Use :meth:`get_write_buffer_limits` to get the limits.
155
Victor Stinnerea3183f2013-12-03 01:08:00 +0100156 .. method:: write(data)
157
158 Write some *data* bytes to the transport.
159
160 This method does not block; it buffers the data and arranges for it
161 to be sent out asynchronously.
162
163 .. method:: writelines(list_of_data)
164
165 Write a list (or any iterable) of data bytes to the transport.
166 This is functionally equivalent to calling :meth:`write` on each
167 element yielded by the iterable, but may be implemented more efficiently.
168
169 .. method:: write_eof()
170
171 Close the write end of the transport after flushing buffered data.
172 Data may still be received.
173
174 This method can raise :exc:`NotImplementedError` if the transport
175 (e.g. SSL) doesn't support half-closes.
176
177
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100178DatagramTransport
179-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100180
181.. method:: DatagramTransport.sendto(data, addr=None)
182
183 Send the *data* bytes to the remote peer given by *addr* (a
184 transport-dependent target address). If *addr* is :const:`None`, the
185 data is sent to the target address given on transport creation.
186
187 This method does not block; it buffers the data and arranges for it
188 to be sent out asynchronously.
189
190.. method:: DatagramTransport.abort()
191
192 Close the transport immediately, without waiting for pending operations
193 to complete. Buffered data will be lost. No more data will be received.
194 The protocol's :meth:`connection_lost` method will eventually be
195 called with :const:`None` as its argument.
196
197
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100198BaseSubprocessTransport
199-----------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100200
201.. class:: BaseSubprocessTransport
202
203 .. method:: get_pid()
204
205 Return the subprocess process id as an integer.
206
Victor Stinnerea3183f2013-12-03 01:08:00 +0100207 .. method:: get_pipe_transport(fd)
208
Brian Curtina1afeec2014-02-08 18:36:14 -0600209 Return the transport for the communication pipe corresponding to the
Victor Stinner4270a242014-10-13 23:56:43 +0200210 integer file descriptor *fd*:
211
212 * ``0``: readable streaming transport of the standard input (*stdin*),
213 or :const:`None` if the subprocess was not created with ``stdin=PIPE``
214 * ``1``: writable streaming transport of the standard output (*stdout*),
215 or :const:`None` if the subprocess was not created with ``stdout=PIPE``
216 * ``2``: writable streaming transport of the standard error (*stderr*),
217 or :const:`None` if the subprocess was not created with ``stderr=PIPE``
218 * other *fd*: :const:`None`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100219
Victor Stinner933a8c82013-12-03 01:59:38 +0100220 .. method:: get_returncode()
221
222 Return the subprocess returncode as an integer or :const:`None`
223 if it hasn't returned, similarly to the
224 :attr:`subprocess.Popen.returncode` attribute.
225
226 .. method:: kill(self)
227
228 Kill the subprocess, as in :meth:`subprocess.Popen.kill`
229
230 On POSIX systems, the function sends SIGKILL to the subprocess.
231 On Windows, this method is an alias for :meth:`terminate`.
232
Victor Stinnerea3183f2013-12-03 01:08:00 +0100233 .. method:: send_signal(signal)
234
235 Send the *signal* number to the subprocess, as in
236 :meth:`subprocess.Popen.send_signal`.
237
238 .. method:: terminate()
239
240 Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`.
241 This method is an alias for the :meth:`close` method.
242
243 On POSIX systems, this method sends SIGTERM to the subprocess.
244 On Windows, the Windows API function TerminateProcess() is called to
245 stop the subprocess.
246
Victor Stinner4270a242014-10-13 23:56:43 +0200247 .. method:: close()
248
249 Ask the subprocess to stop by calling the :meth:`terminate` method if the
250 subprocess hasn't returned yet, and close transports of all pipes
251 (*stdin*, *stdout* and *stderr*).
252
Victor Stinnerea3183f2013-12-03 01:08:00 +0100253
Victor Stinner9592edb2014-02-02 15:03:02 +0100254.. _asyncio-protocol:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100255
256Protocols
257=========
258
259:mod:`asyncio` provides base classes that you can subclass to implement
260your network protocols. Those classes are used in conjunction with
Victor Stinner9592edb2014-02-02 15:03:02 +0100261:ref:`transports <asyncio-transport>` (see below): the protocol parses incoming
Victor Stinnerea3183f2013-12-03 01:08:00 +0100262data and asks for the writing of outgoing data, while the transport is
263responsible for the actual I/O and buffering.
264
265When subclassing a protocol class, it is recommended you override certain
266methods. Those methods are callbacks: they will be called by the transport
267on certain events (for example when some data is received); you shouldn't
268call them yourself, unless you are implementing a transport.
269
270.. note::
271 All callbacks have default implementations, which are empty. Therefore,
272 you only need to implement the callbacks for the events in which you
273 are interested.
274
275
276Protocol classes
277----------------
278
279.. class:: Protocol
280
281 The base class for implementing streaming protocols (for use with
282 e.g. TCP and SSL transports).
283
284.. class:: DatagramProtocol
285
286 The base class for implementing datagram protocols (for use with
287 e.g. UDP transports).
288
289.. class:: SubprocessProtocol
290
291 The base class for implementing protocols communicating with child
292 processes (through a set of unidirectional pipes).
293
294
295Connection callbacks
296--------------------
297
Victor Stinner15386652014-06-10 09:19:26 +0200298These callbacks may be called on :class:`Protocol`, :class:`DatagramProtocol`
299and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100300
301.. method:: BaseProtocol.connection_made(transport)
302
303 Called when a connection is made.
304
305 The *transport* argument is the transport representing the
306 connection. You are responsible for storing it somewhere
307 (e.g. as an attribute) if you need to.
308
309.. method:: BaseProtocol.connection_lost(exc)
310
311 Called when the connection is lost or closed.
312
313 The argument is either an exception object or :const:`None`.
314 The latter means a regular EOF is received, or the connection was
315 aborted or closed by this side of the connection.
316
Victor Stinner15386652014-06-10 09:19:26 +0200317:meth:`~BaseProtocol.connection_made` and :meth:`~BaseProtocol.connection_lost`
318are called exactly once per successful connection. All other callbacks will be
319called between those two methods, which allows for easier resource management
320in your protocol implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100321
322The following callbacks may be called only on :class:`SubprocessProtocol`
323instances:
324
325.. method:: SubprocessProtocol.pipe_data_received(fd, data)
326
327 Called when the child process writes data into its stdout or stderr pipe.
328 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
329 bytes object containing the data.
330
331.. method:: SubprocessProtocol.pipe_connection_lost(fd, exc)
332
333 Called when one of the pipes communicating with the child process
334 is closed. *fd* is the integer file descriptor that was closed.
335
336.. method:: SubprocessProtocol.process_exited()
337
338 Called when the child process has exited.
339
340
Victor Stinnerea3183f2013-12-03 01:08:00 +0100341Streaming protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100342-------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
344The following callbacks are called on :class:`Protocol` instances:
345
346.. method:: Protocol.data_received(data)
347
348 Called when some data is received. *data* is a non-empty bytes object
349 containing the incoming data.
350
351 .. note::
352 Whether the data is buffered, chunked or reassembled depends on
353 the transport. In general, you shouldn't rely on specific semantics
354 and instead make your parsing generic and flexible enough. However,
355 data is always received in the correct order.
356
357.. method:: Protocol.eof_received()
358
359 Calls when the other end signals it won't send any more data
360 (for example by calling :meth:`write_eof`, if the other end also uses
361 asyncio).
362
363 This method may return a false value (including None), in which case
364 the transport will close itself. Conversely, if this method returns a
365 true value, closing the transport is up to the protocol. Since the
366 default implementation returns None, it implicitly closes the connection.
367
368 .. note::
369 Some transports such as SSL don't support half-closed connections,
370 in which case returning true from this method will not prevent closing
371 the connection.
372
373:meth:`data_received` can be called an arbitrary number of times during
374a connection. However, :meth:`eof_received` is called at most once
375and, if called, :meth:`data_received` won't be called after it.
376
377Datagram protocols
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100378------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100379
380The following callbacks are called on :class:`DatagramProtocol` instances.
381
382.. method:: DatagramProtocol.datagram_received(data, addr)
383
384 Called when a datagram is received. *data* is a bytes object containing
385 the incoming data. *addr* is the address of the peer sending the data;
386 the exact format depends on the transport.
387
388.. method:: DatagramProtocol.error_received(exc)
389
390 Called when a previous send or receive operation raises an
391 :class:`OSError`. *exc* is the :class:`OSError` instance.
392
393 This method is called in rare conditions, when the transport (e.g. UDP)
394 detects that a datagram couldn't be delivered to its recipient.
395 In many conditions though, undeliverable datagrams will be silently
396 dropped.
397
398
399Flow control callbacks
400----------------------
401
Larry Hastings3732ed22014-03-15 21:13:56 -0700402These callbacks may be called on :class:`Protocol`,
403:class:`DatagramProtocol` and :class:`SubprocessProtocol` instances:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100404
405.. method:: BaseProtocol.pause_writing()
406
407 Called when the transport's buffer goes over the high-water mark.
408
409.. method:: BaseProtocol.resume_writing()
410
411 Called when the transport's buffer drains below the low-water mark.
412
413
414:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
415:meth:`pause_writing` is called once when the buffer goes strictly over
416the high-water mark (even if subsequent writes increases the buffer size
417even more), and eventually :meth:`resume_writing` is called once when the
418buffer size reaches the low-water mark.
419
420.. note::
421 If the buffer size equals the high-water mark,
422 :meth:`pause_writing` is not called -- it must go strictly over.
423 Conversely, :meth:`resume_writing` is called when the buffer size is
424 equal or lower than the low-water mark. These end conditions
425 are important to ensure that things go as expected when either
426 mark is zero.
427
Larry Hastings3732ed22014-03-15 21:13:56 -0700428.. note::
429 On BSD systems (OS X, FreeBSD, etc.) flow control is not supported
430 for :class:`DatagramProtocol`, because send failures caused by
431 writing too many packets cannot be detected easily. The socket
432 always appears 'ready' and excess packets are dropped; an
433 :class:`OSError` with errno set to :const:`errno.ENOBUFS` may or
434 may not be raised; if it is raised, it will be reported to
435 :meth:`DatagramProtocol.error_received` but otherwise ignored.
436
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100438Coroutines and protocols
439------------------------
440
441Coroutines can be scheduled in a protocol method using :func:`async`, but there
R David Murray64f10d42014-11-02 12:32:26 -0500442is no guarantee made about the execution order. Protocols are not aware of
443coroutines created in protocol methods and so will not wait for them.
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100444
Victor Stinner9592edb2014-02-02 15:03:02 +0100445To have a reliable execution order, use :ref:`stream objects <asyncio-streams>` in a
Victor Stinner4b4f9eb2014-01-24 17:33:20 +0100446coroutine with ``yield from``. For example, the :meth:`StreamWriter.drain`
447coroutine can be used to wait until the write buffer is flushed.
448
449
Victor Stinner04e6df32014-10-11 16:16:27 +0200450Protocol examples
451=================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
Victor Stinnered051592014-10-12 20:18:16 +0200453.. _asyncio-tcp-echo-client-protocol:
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100454
Victor Stinnered051592014-10-12 20:18:16 +0200455TCP echo client protocol
456------------------------
457
458TCP echo client using the :meth:`BaseEventLoop.create_connection` method, send
459data and wait until the connection is closed::
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100460
461 import asyncio
462
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200463 class EchoClientProtocol(asyncio.Protocol):
Victor Stinner53664342014-10-12 11:35:09 +0200464 def __init__(self, message, loop):
465 self.message = message
466 self.loop = loop
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100467
468 def connection_made(self, transport):
Victor Stinner31d83222013-12-04 11:16:17 +0100469 transport.write(self.message.encode())
Victor Stinner53664342014-10-12 11:35:09 +0200470 print('Data sent: {!r}'.format(self.message))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100471
472 def data_received(self, data):
Victor Stinner53664342014-10-12 11:35:09 +0200473 print('Data received: {!r}'.format(data.decode()))
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100474
475 def connection_lost(self, exc):
Victor Stinner53664342014-10-12 11:35:09 +0200476 print('The server closed the connection')
477 print('Stop the event lop')
478 self.loop.stop()
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100479
480 loop = asyncio.get_event_loop()
Victor Stinner53664342014-10-12 11:35:09 +0200481 message = 'Hello World!'
482 coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
483 '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100484 loop.run_until_complete(coro)
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100485 loop.run_forever()
486 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100487
Victor Stinnera881a7f2013-12-09 13:19:23 +0100488The event loop is running twice. The
489:meth:`~BaseEventLoop.run_until_complete` method is preferred in this short
490example to raise an exception if the server is not listening, instead of
491having to write a short coroutine to handle the exception and stop the
492running loop. At :meth:`~BaseEventLoop.run_until_complete` exit, the loop is
Andrew Svetlov588517c2014-07-23 11:27:17 +0300493no longer running, so there is no need to stop the loop in case of an error.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100494
Victor Stinnered051592014-10-12 20:18:16 +0200495.. seealso::
Victor Stinnerc2721b42014-10-12 11:13:40 +0200496
Victor Stinnered051592014-10-12 20:18:16 +0200497 The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
498 example uses the :func:`asyncio.open_connection` function.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100499
Victor Stinnered051592014-10-12 20:18:16 +0200500
501.. _asyncio-tcp-echo-server-protocol:
502
503TCP echo server protocol
504------------------------
505
506TCP echo server using the :meth:`BaseEventLoop.create_server` method, send back
507received data and close the connection::
Victor Stinnera881a7f2013-12-09 13:19:23 +0100508
509 import asyncio
510
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200511 class EchoServerClientProtocol(asyncio.Protocol):
Victor Stinnera881a7f2013-12-09 13:19:23 +0100512 def connection_made(self, transport):
513 peername = transport.get_extra_info('peername')
Victor Stinnerc2721b42014-10-12 11:13:40 +0200514 print('Connection from {}'.format(peername))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100515 self.transport = transport
516
517 def data_received(self, data):
Victor Stinnerc2721b42014-10-12 11:13:40 +0200518 message = data.decode()
519 print('Data received: {!r}'.format(message))
520
521 print('Send: {!r}'.format(message))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100522 self.transport.write(data)
523
Victor Stinner53664342014-10-12 11:35:09 +0200524 print('Close the client socket')
Victor Stinnera881a7f2013-12-09 13:19:23 +0100525 self.transport.close()
526
527 loop = asyncio.get_event_loop()
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200528 # Each client connection will create a new protocol instance
529 coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100530 server = loop.run_until_complete(coro)
Victor Stinnera881a7f2013-12-09 13:19:23 +0100531
Victor Stinnered051592014-10-12 20:18:16 +0200532 # Serve requests until CTRL+c is pressed
Victor Stinnerc2721b42014-10-12 11:13:40 +0200533 print('Serving on {}'.format(server.sockets[0].getsockname()))
Victor Stinnera881a7f2013-12-09 13:19:23 +0100534 try:
535 loop.run_forever()
536 except KeyboardInterrupt:
Victor Stinnered051592014-10-12 20:18:16 +0200537 pass
Victor Stinnerc2721b42014-10-12 11:13:40 +0200538
539 # Close the server
540 server.close()
541 loop.run_until_complete(server.wait_closed())
542 loop.close()
Victor Stinnera881a7f2013-12-09 13:19:23 +0100543
R David Murray530a69f2013-12-14 11:26:06 -0500544:meth:`Transport.close` can be called immediately after
Victor Stinnera881a7f2013-12-09 13:19:23 +0100545:meth:`WriteTransport.write` even if data are not sent yet on the socket: both
546methods are asynchronous. ``yield from`` is not needed because these transport
Larry Hastings3732ed22014-03-15 21:13:56 -0700547methods are not coroutines.
Victor Stinnera881a7f2013-12-09 13:19:23 +0100548
Victor Stinnered051592014-10-12 20:18:16 +0200549.. seealso::
550
551 The :ref:`TCP echo server using streams <asyncio-tcp-echo-server-streams>`
552 example uses the :func:`asyncio.start_server` function.
553
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200554
555.. _asyncio-udp-echo-client-protocol:
556
557UDP echo client protocol
558------------------------
559
560UDP echo client using the :meth:`BaseEventLoop.create_datagram_endpoint`
561method, send data and close the transport when we received the answer::
562
563 import asyncio
564
565 class EchoClientProtocol:
566 def __init__(self, message, loop):
567 self.message = message
568 self.loop = loop
569 self.transport = None
570
571 def connection_made(self, transport):
572 self.transport = transport
573 print('Send:', self.message)
574 self.transport.sendto(self.message.encode())
575
576 def datagram_received(self, data, addr):
577 print("Received:", data.decode())
578
579 print("Close the socket")
580 self.transport.close()
581
582 def error_received(self, exc):
583 print('Error received:', exc)
584
585 def connection_lost(self, exc):
586 print("Socket closed, stop the event loop")
587 loop = asyncio.get_event_loop()
588 loop.stop()
589
590 loop = asyncio.get_event_loop()
591 message = "Hello World!"
592 connect = loop.create_datagram_endpoint(
593 lambda: EchoClientProtocol(message, loop),
594 remote_addr=('127.0.0.1', 9999))
595 transport, protocol = loop.run_until_complete(connect)
596 loop.run_forever()
597 transport.close()
598 loop.close()
599
600
601.. _asyncio-udp-echo-server-protocol:
602
603UDP echo server protocol
604------------------------
605
606UDP echo server using the :meth:`BaseEventLoop.create_datagram_endpoint`
607method, send back received data::
608
609 import asyncio
610
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200611 class EchoServerProtocol:
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200612 def connection_made(self, transport):
613 self.transport = transport
614
615 def datagram_received(self, data, addr):
616 message = data.decode()
617 print('Received %r from %s' % (message, addr))
618 print('Send %r to %s' % (message, addr))
619 self.transport.sendto(data, addr)
620
621 loop = asyncio.get_event_loop()
622 print("Starting UDP server")
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200623 # One protocol instance will be created to serve all client requests
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200624 listen = loop.create_datagram_endpoint(
Victor Stinnercfbea3a2014-10-12 11:30:17 +0200625 EchoServerProtocol, local_addr=('127.0.0.1', 9999))
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200626 transport, protocol = loop.run_until_complete(listen)
627
628 try:
629 loop.run_forever()
630 except KeyboardInterrupt:
631 pass
632
633 transport.close()
634 loop.close()
635
636
Victor Stinner04e6df32014-10-11 16:16:27 +0200637.. _asyncio-register-socket:
Victor Stinnera881a7f2013-12-09 13:19:23 +0100638
Victor Stinner04e6df32014-10-11 16:16:27 +0200639Register an open socket to wait for data using a protocol
640---------------------------------------------------------
641
642Wait until a socket receives data using the
643:meth:`BaseEventLoop.create_connection` method with a protocol, and then close
644the event loop ::
645
646 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200647 try:
648 from socket import socketpair
649 except ImportError:
650 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200651
652 # Create a pair of connected sockets
Victor Stinnerccd8e342014-10-11 16:30:02 +0200653 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200654 loop = asyncio.get_event_loop()
655
656 class MyProtocol(asyncio.Protocol):
657 transport = None
658
659 def connection_made(self, transport):
660 self.transport = transport
661
662 def data_received(self, data):
663 print("Received:", data.decode())
664
665 # We are done: close the transport (it will call connection_lost())
666 self.transport.close()
667
668 def connection_lost(self, exc):
669 # The socket has been closed, stop the event loop
670 loop.stop()
671
672 # Register the socket to wait for data
673 connect_coro = loop.create_connection(MyProtocol, sock=rsock)
674 transport, protocol = loop.run_until_complete(connect_coro)
675
676 # Simulate the reception of data from the network
677 loop.call_soon(wsock.send, 'abc'.encode())
678
679 # Run the event loop
680 loop.run_forever()
681
682 # We are done, close sockets and the event loop
683 rsock.close()
684 wsock.close()
685 loop.close()
686
687.. seealso::
688
689 The :ref:`watch a file descriptor for read events
690 <asyncio-watch-read-event>` example uses the low-level
691 :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a
692 socket.
693
694 The :ref:`register an open socket to wait for data using streams
695 <asyncio-register-socket-streams>` example uses high-level streams
696 created by the :func:`open_connection` function in a coroutine.