# -*- coding:utf-8 -*- #放在Linux下运行 # socketserver一共有这么几种类型 # # class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True) # This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server. # # class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True) # This uses datagrams, which are discrete packets of information that may arrive out of order or be lost while in transit. The parameters are the same as for TCPServer. # import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): #每个请求都会走这里 while True: try : self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) self.request.send(self.data.upper()) except ConnectionResetError as e: print(e) break if __name__ == "__main__": HOST, PORT = "localhost", 9999 #多线程 server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) #修改的地方 #多进程(window下不行,Linux下可以) # ForkingTCPServer 每来一个请求,启动一个进程,太费资源 pass #server = socketserver.ForkingTCPServer((HOST, PORT), MyTCPHandler) #修改的地方 server.serve_forever()