socketserver模块就是socket模块的封装。
The socketserver
module simplifies the task of writing network servers.
socketserver一共有这么几种类型
1
|
class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate = True ) |
This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server.
1
|
class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate = True ) |
This uses datagrams, which are discrete packets of information that may arrive out of order or be lost while in transit. The parameters are the same as for TCPServer
.
1
2
|
class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate = True ) class socketserver.UnixDatagramServer(server_address, RequestHandlerClass,bind_and_activate = True ) |
These more infrequently used classes are similar to the TCP and UDP classes, but use Unix domain sockets; they’re not available on non-Unix platforms. The parameters are the same as for TCPServer
.
There are five classes in an inheritance diagram, four of which represent synchronous servers of four types:
+------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
创建一个socketserver 至少分以下几步:
First, you must create a request handler处理类 class by subclassing the BaseRequestHandler class and overriding覆盖
its handle() method; this method will process incoming requests.
你必须自己创建一个请求处理类,并且这个类要继承BaseRequestHandler,并且还有重写父亲类里的handle()
Second, you must instantiate实例化 one of the server classes, passing it the server’s address and the request handler class.
你必须实例化TCPServer ,并且传递server ip 和 你上面创建的请求处理类 给这个TCPServer
Then call the handle_request() or serve_forever() method of the server object to process one or many requests.
server.handle_request() #只处理一个请求
server.serve_forever() #处理多个一个请求,永远执行
让你的socketserver并发起来, 必须选择使用以下一个多并发的类
class socketserver.
ForkingTCPServer
class socketserver.
ForkingUDPServer
class socketserver.
ThreadingTCPServer
class socketserver.
ThreadingUDPServer
基本的socketserver代码
1 import socketserver 2 3 class MyTCPHandler(socketserver.BaseRequestHandler): 4 def handle(self): 5 while True: 6 try: 7 self.data = self.request.recv(1024).strip() 8 print("{} wrote:".format(self.client_address[0])) 9 print(self.data) 10 self.request.send(self.data.upper()) 11 except ConnectionResetError as e: 12 print("err",e) 13 break 14 if __name__ == "__main__": 15 HOST, PORT = "localhost", 9999 16 # Create the server, binding to localhost on port 9999 17 server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) 18 server.serve_forever()