Overview of Python socketserver.UDPServer with Example

Class UDPServer simplifies the creation of UDP based network servers. An example of using UDPServer along with DatagramRequestHandler is given

Udpserver Updated 20 Feb 2017 2 min read

Overview

  • A server based on the UDP protocol processes datagrams received from its UDP based clients. Unlike a TCP Server, an UDP server does not maintain a persistent connection that can be used for streaming data to its clients.

  • UDP based servers are suitable for message oriented communications where loss of some datagrams is acceptable for both the clients and servers.

  • An UDP based network server can be created using the class UDPServer from Python’s socketserver module.

Server Creation

  • A request handler class is required to be defined to handle the incoming UDP messages from the clients.

  • A tuple containing the IP address of the server and the port on which it listens needs to be created.

  • An instance of UDPServer needs to be constructed by passing the tuple with server IP and port number and the request handler class

  • To make the UDP server listen continuously for incoming messages the serve_forever() method should be called.

Handling Request from Clients

  • The DatagramRequestHandler class provides a base from which datagram-based request handlers can be defined.

  • In the example program below, the class MyUDPHandler is derived from DatagramRequestHandler.

  • The handle()method is overridden which forms the core of the message handling from UDP clients.

  • Messages from the clients are read from the rfile attribute.

  • Messages are sent to clients by writing to wfile attribute.

  • The client part of the UDP client-server program written with the POSIX API is used to test the UDP Server.

Example

python
import socketserver

# define a subclass of UDPServer

class MyUDPHandler(socketserver.DatagramRequestHandler):

    def handle(self):

        # Receive a message from a client

        print("Got an UDP Message from {}".format(self.client_address[0]))

        msgRecvd = self.rfile.readline().strip()

        print("The Message is {}".format(msgRecvd))

        # Send a message from a client

        self.wfile.write("Hello UDP Client! I received a message from you!".encode())

server_IP       = "127.0.0.1"

server_port     = 7070

serverAddress   = (server_IP, server_port)

serverUDP = socketserver.UDPServer(serverAddress, MyUDPHandler)

serverUDP.serve_forever()

Output – Server Side

Output
Got an UDP Message from 127.0.0.1

The Message is b'Hello UDP Server'

Output – Client Side

Output
Message from Server b'Hello UDP Client! I received a message from you!'