Udp Server and Client

This example illustrates how to write a UDP Echo server and client pair. The code for this example is located in the examples.echoudp.manage module.

Run The example

To run the server:

python manage.py

Open a new shell, in this directory, launch python and type:

>>> from manage import Echo
>>> echo = Echo(('localhost', 8060))
>>> echo(b'Hello!\n')
b'Hello!'

Writing the Client

The first step is to write a small class handling a connection pool with the remote server. The Echo class does just that, it subclass the handy AbstractUdpClient and uses the asynchronous Pool of connections as backbone.

The second step is the implementation of the EchoUdpProtocol, a subclass of DatagramProtocol. The EchoUdpProtocol is needed for two reasons:

  • It encodes and sends the request to the remote server
  • It listens for incoming data from the remote server via the datagram_received() method.

Implementation

Echo UDP Protocol

class examples.echoudp.manage.EchoUdpProtocol(loop, session=1, producer=None, logger=None, **kw)[source]

A base DatagramProtocol for UDP echo clients and servers.

The only difference between client and server is the implementation of the response() method.

datagram_received(data, addr)[source]

Handle data from addr.

response(data, addr)[source]

Abstract response handler

Echo Client

class examples.echoudp.manage.Echo(address, pool_size=5, loop=None)[source]

A client for the echo server.

Parameters:
  • address – set the address attribute
  • pool_size – used when initialising the connection pool.
  • loop – Optional event loop to set the _loop attribute.
_loop

The event loop used by the client IO requests.

The event loop is stored at this attribute so that asynchronous method decorators such as task() can be used.

address

remote server UDP address.

pool

Asynchronous client protocol Pool.

__call__(message)[source]

Send a message to the server and wait for a response.

Returns:a Future

Echo Server

examples.echoudp.manage.server(name=None, description=None, **kwargs)[source]

Create the UdpSocketServer.