socket服务器集成模块

python2 SocketServer
python3 socketserver

1.功能:
通过模块的接口完成基于多进程/多线程的tcp/udp的socket并发程序

2.模块类:
DatagramRequestHandler 处理udp请求
StreamRequestHandler 处理tcp请求

UDPServer 提供udp服务端类
TCPServer 提供tcp服务端类

ForkingMixIn 提供进程创建
ForkingTCPServer <—> ForkingMixIn + TCPServer
ForkingUDPServer <—> ForkingMixIn + UDPServer

ThreadingMixIn 提供线程创建
ThreadingTCPServer <—> ThreadingMixIn + TCPServer
ThreadingUDPServer <—> ThreadingMixIn + UDPServer

四种并发:
进程tcp并发
‘ForkingMixIn’,‘TCPServer’,‘StreamRequestHandler’,
进程udp并发
‘ForkingMixIn’,‘UDPServer’,‘DatagramRequestHandler’,
线程tcp并发
‘ThreadingMixIn’,‘TCPServer’,‘StreamRequestHandler’,
线程udp并发
‘ThreadingMixIn’,‘UDPServer’,‘DatagramRequestHandler’,
‘ForkingTCPServer’
进程tcp并发+线程tcp并发
‘ForkingUDPServer’,
进程udp并发+线程udp并发


3.示例:

from socketserver import *

# 创建多进程tcp并发

# 创建进程tcp服务器类
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).decode()
	    if not data:
	        break
	    print(data)
	    self.request.send(b'Receive your message')

# 生成服务器对象,传入addr和具体处理类
server = Server(('0.0.0.0',8888),Handler)

# 启动服务器
server.serve_forever()
from socketserver import *

# 多进程udp并发
class Server(ForkingMixIn,UDPServer):
    pass

class Handler(DatagramRequestHandler):
    def handle(self):
        while True:
            # 接收消息
            data = self.rfile.readline()
            if not data:
                break
            print(data)
            # 发送消息
            self.wfile.write(b'Receive your message')

server = Server(('127.0.0.1',8888),Handler)
server.serve_forever()

你可能感兴趣的:(python网络编程,python,socket)