基于tcp的套接字(实现并发),关键就是两个循环,一个链接循环,一个通信循环
基于udp的套接字(不是正真意义上的并发,实现真并发)
socketserver模块中分两大类:server类(解决链接问题)和request类(解决通信问题)
# 服务端必须满足至少三点:
# 1. 绑定一个固定的ip和port
# 2. 一直对外提供服务,稳定运行
# 3. 能够支持并发
import socketserver
# 自定义类用来处理通信循环
class MyTCPhanler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
data = self.request.recv(1024)
if len(data) == 0: break # 针对linux系统
print('-->收到客户端的消息: ', data)
self.request.send(data.upper())
except ConnectionResetError:
break
self.request.close()
if __name__ == '__main__':
server=socketserver.ThreadingTCPServer(('127.0.0.1',8081),MyTCPhanler)
#
# 1 server_address, RequestHandlerClass
# 2 拿到tcp套接字对象 s.socket=p
# 3 bind
# 4 listen
server.serve_forever() # 链接循环
# 1 conn,adress=p.accept()
# 2 拿conn创线程 target=xxxxx 里面调MyTCPhanler
import socketserver
class MyUdphandler(socketserver.BaseRequestHandler):
def handle(self):
data,sock=self.request
sock.sendto(data.upper(),self.client_address)
if __name__ == '__main__':
server=socketserver.ThreadingUDPServer(('127.0.0.1',8081),MyUdphandler)
server.serve_forever()