Python SocketServer Module
The socketserver module simplifies the task of writing network servers. It provides classes for handling TCP, UDP, and Unix domain sockets.
Importing the Module
import socketserver
Creating a Request Handler
To create a request handler, you must subclass socketserver.BaseRequestHandler and override the handle() method.
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
Creating a Server
You can create a server by instantiating one of the server classes, passing the server address and the request handler class.
TCP Server
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
UDP Server
For UDP, use socketserver.UDPServer and socketserver.DatagramRequestHandler (optional but recommended for convenience).
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("{} wrote:".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
HOST, PORT = "localhost", 9999
with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
server.serve_forever()
Threading and Forking
To make the server asynchronous (handle multiple requests simultaneously), you can use the ThreadingMixIn or ForkingMixIn classes.
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass