继承模块的使用 python2 SocketServer python3 socketserver
功能:通过模块的不同、类的组合完成多进程/多线程的tcp/udp的并发
StreamRequestHandler 处理TCP套接字请求
DatagramRequestHandler 处理udp套接字请求
TCPServer 创建tcp server
UDPServer 创建udp server
ForkingMixIn 创建多进程
ForkingTCPServer -->ForkingMinIn + TCPServer
ForkingUDPServer -->ForkingMinIn + UDPServer
ThreadingMixIn 创建多线程
ThreadingTCPServer --> ThreadingMinIn + TCPServer
ThreadingUDPServer --> ThreadingMinIn + UDPServer
'ThreadingUnixDatagramServer',
'ThreadingUnixStreamServer',
tcp多进程并发服务端的使用
from socketserver import *
#创建服务器类
class Server(ForkingMixIn,TCPServer):
pass
class Handler(StreamRequestHandler):
def handle(self):
#self.request -->accept 返回的套接字
print('Connect from',\
self.request.getpeername())
while True:
data = self.request.recv(1024)
if not data:
print('quit from:',self.request.getpeername())
break
print(data.decode())
self.request.send(b'Received')
if __name__ == "__main__":
server_addr = ('0.0.0.0',8888)
#创建服务器对象
server = Server(server_addr,Handler)
#启动服务器
server.serve_forever()
多进程并发udp服务器的使用
from socketserver import *
#创建服务器类
class Server(ForkingMixIn,UDPServer):
pass
class Handler(DatagramRequestHandler):
def handle(self):
while True:
data = self.rfile.readline(1024)
print(self.client_address)
if not data:
break
print(data.decode())
self.wfile.write(b'Received')
if __name__ == "__main__":
server_addr = ('0.0.0.0',8888)
#创建服务器对象
server = Server(server_addr,Handler)
#启动服务器
server.serve_forever()