Overview:
A TCP Server program can be created using the classes
- TCPServer
- StreamRequestHandler
from the socketserver module of Python Standard Library.
The steps involved in creating a TCP Server and request handling are given here with an example. The client part of TCP client-server program written with POSIX API is used to connect to the example TCP Server program.
Server Creation:
- TCP based server programs can be created using the socket.TCPServer class.
- The TCPServer class is a class derived from the socketserver.BaseServer which provides a generic interface for network servers.
- Once a TCPServer instance is created, it can be supplied with a
- A tuple containing the IP address and Port Number
- Request handler to handle incoming requests from the client
- To handle requests for a TCP server the socketserver provided StreamRequestHandler could be used.
- StreamRequestHandler class is a specialized, sub-class of BaseRequestHandler.
- StreamRequestHandler acts as a base request handler for TCP based servers, which provide connection oriented, streaming and reliable communication over the network.
- To start the TCP server method serve_forever() needs to be called on the TCPServer instance.
Handling Requests from Clients:
- Though StreamRequestHandler forms the base for TCP based request handlers – it further delegates the implementation of handle()method to the sub-classes.
- In the sample program below class MyTCPRequestHandler is derived from StreamRequestHandler.
- MyTCPRequestHandler overrides the handle() method and this forms the core of handling data sent from the client connections.
- StreamRequestHandler derived instances has got two attributes that help in the data exchange between the client and server.
- The attribute wfile is used to write any content that needs to be sent to the client.
- The attribute rfile is used to write any content that needs to be received from the client.
Example:
# import the socketserver module of Python import socketserver
# Create a Request Handler # In this TCP server case - the request handler is derived from StreamRequestHandler class MyTCPRequestHandler(socketserver.StreamRequestHandler):
# handle() method will be called once per connection def handle(self): # Receive and print the data received from client print("Recieved one request from {}".format(self.client_address[0])) msg = self.rfile.readline().strip() print("Data Recieved from client is:".format(msg)) print(msg)
# Send some data to client self.wfile.write("Hello Client....Got your message".encode())
# Create a TCP Server instance aServer = socketserver.TCPServer(("127.0.0.1", 9090), MyTCPRequestHandler)
# Listen for ever aServer.serve_forever()
|
Output – Server Side:
Recieved one request from 127.0.0.1 Data Recieved from client is: b'GET / HTTP/1.1' |
Output – Client Side:
Connected to localhost b'Hello Client....Got your message' b'' Connection closed |