每个服务器类中最主要的是有两个子类:
BaseHTTPServer:
HTTPServer
BaseHTTPRequestHandler
SocketServer
TCPServer
BaseRequestHandler
SocketServer有四个基本的子类: TCPServer, UDPServer,UnixStreamServer and UnixDatagramServer
创建一个server需要以下几个步骤:
1 you must create a request handler class by subclassing the BaseRequestHandler class and overriding its handle() method,,handle()方法主要是接受输入的请求。
2 you must instantiate one of the server classes(server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)), passing it the server’s address and the request handler class
3 call the handle_request() or serve_forever() method of the server object to process one or many requests
结构图:
+------------+ | BaseServer | +------------+ | v +-----------+ +------------------+ | TCPServer |------->| UnixStreamServer | +-----------+ +------------------+ | v +-----------+ +--------------------+ | UDPServer |------->| UnixDatagramServer | +-----------+ +--------------------+
server code:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "%s wrote:" % self.client_address[0]
print self.data
# just send back the same data, but upper-cased
self.request.send(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()