#socketserver使用的的四个步骤
#1、创建一个请求的处理类,它是BaseReauestHanndler子类,并且重写父类的handler的方法
#2、实例化一个服务类(TCPServer、UTPServer、UnixStreamServer、UnixDatagramServer)
#并且对实例化的服务类(如:TCPServer)将实例化的handler的方法当参数传入
#3、调用实例化服务类的handler的方法,(如:server.server_forever()),处理请求。
#4、通过server.close()关闭服务
ex:服务端
1 import socketserver 2 class MyTCPServer(socketserver.BaseRequestHandler): 3 def handle(self): 4 while True: 5 try: 6 self.data = self.request.recv(1024).strip() 7 print("{} wrote:".format(self.client_address[0])) 8 print(self.data) 9 self.request.send(self.data.upper()) 10 except ConnectionResetError as e: 11 print("err",e) 12 break 13 if __name__ == "__main__": 14 HOST, PORT = "localhost", 9999 15 # Create the server, binding to localhost on port 9999 16 server = socketserver.ThreadingTCPServer((HOST, PORT),MyTCPServer)#ThreadingTCPServer多线程 17 server.serve_forever() 18 server.server_close()
ex:客户端
1 import socket 2 client=socket.socket()#声明socket类型,同时生成连接对象 3 client.connect(('localhost',9999)) 4 5 while True: 6 msg=input(">>:").strip() 7 if len(msg)==0:#当输入的消息是空时,不发送,等待输入非空后再发送 8 continue 9 client.send(msg.encode("utf-8")) 10 data=client.recv(1024) 11 print("recv:",data.decode()) 12 client.close()