SocketServer
常用类:
socketserver.
TCPServer() # 一对一
socketserver.Threading
TCPServer() # 多并发
socketserver.
UDPServer() #
一对一
socketserver.
Threading
UDPServer()
# 多并发
不常用类:
socketserver.
UnixStreamServer()
socketserver.
UnixDatagramServer()
创建 socketserver
Request Handler Objects
class socketserver.
BaseRequestHandler
This is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new handle()
method, and can override any of the other methods. A new instance of the subclass is created for each request.
setup
()-
Called before the
handle()
method to perform any initialization actions required. The default implementation does nothing.
handle
()-
This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as
self.request
; the client address asself.client_address
; and the server instance asself.server
, in case it needs access to per-server information.The type of
self.request
is different for datagram or stream services. For stream services,self.request
is a socket object; for datagram services,self.request
is a pair of string and socket.
finish
()-
Called after the
handle()
method to perform any clean-up actions required. The default implementation does nothing. Ifsetup()
raises an exception, this function will not be called.
1 import socketserver 2 3 4 # 第一步 创建一个handler类,继承socketserver.BaseRequestHandler 5 class TCPHandler(socketserver.BaseRequestHandler): 6 7 # 重写handle方法 8 def handle(self): 9 10 while True: 11 try: 12 self.data = self.request.recv(1024).strip() 13 print('from %s' % self.client_address[0]) 14 print(self.data) 15 self.request.send(self.data.upper()) 16 except ConnectionResetError as e: 17 print(self.client_address, e) 18 break 19 20 if __name__ == '__main__': 21 22 HOST, POST = 'localhost', 9999 23 # 第二步 实例化一个server,把(HOST, POST)和上面的handler类传进去 24 server = socketserver.ThreadingTCPServer((HOST, POST), TCPHandler) 25 # ForkingTCPServer 多进程--这个在windows上不好使 26 # server = socketserver.ForkingTCPServer((HOST, POST), TCPHandler) 27 # 第三部,开启服务,serve_forever(),处理多个请求,永远执行 28 server.serve_forever()
上面是一个最基本的写法