二、基于socketserver模块实现并发tcp套接字通信
#server
# from socket import * # # # server=socket(AF_INET,SOCK_STREAM) # server.bind(('127.0.0.1',8080)) # server.listen(5) # # while True: # conn,addr=server.accept() # print(addr) # # while True: # try: # data=conn.recv(1024) # if len(data) == 0:break # conn.send(data.upper()) # except Exception: # break # # conn.close() # 支持并发版本 import socketserver class MyRequestHandler(socketserver.BaseRequestHandler): def handle(self): # 处理通信 print(self.client_address) while True: try: data = self.request.recv(1024) # self.request=>conn if len(data) == 0: break self.request.send(data.upper()) except Exception: break self.request.close() if __name__ == '__main__': s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyRequestHandler, bind_and_activate=True) s.serve_forever()
#client
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: msg=input(">>: ").strip() if len(msg) == 0: continue client.send(msg.encode('utf-8')) data=client.recv(1024) print(data.decode('utf-8'))
三、基于socketserver模块实现并发udp套接字通信
#server
import socketserver class MyRequestHandler(socketserver.BaseRequestHandler): def handle(self): # 处理通信 data,server=self.request server.sendto(data.upper(),self.client_address) if __name__ == '__main__': s = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyRequestHandler, bind_and_activate=True) s.serve_forever()
#client
from socket import * client = socket(AF_INET, SOCK_DGRAM) while True: msg = input('>>: ').strip() client.sendto(msg.encode("utf-8"), ('127.0.0.1', 8080)) data, server_addr = client.recvfrom(1024) print(data.decode('utf-8'))
---33---