A UDP server is easily created using the socketserver
library.
a simple time server:
import time
from socketserver import BaseRequestHandler, UDPServer
class CtimeHandler(BaseRequestHandler):
def handle(self):
print('connection from: ', self.client_address)
# Get message and client socket
msg, sock = self.request
resp = time.ctime()
sock.sendto(resp.encode('ascii'), self.client_address)
if __name__ == '__main__':
server = UDPServer(('', 5000), CtimeHandler)
server.serve_forever()
Testing:
>>> from socket import socket, AF_INET, SOCK_DGRAM
>>> sock = socket(AF_INET, SOCK_DGRAM)
>>> sick.sendto(b'', ('localhost', 5000))
0
>>> sock.recvfrom(8192)
(b'Wed Aug 15 20:35:08 2012', ('127.0.0.1', 5000))