这篇文章主要为大家展示了如何使用python中socketserver,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
socketserver的介绍:
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): try: while True: self.data=self.request.recv(1024) print("{} send:".format(self.client_address),self.data) if not self.data: print("connection lost") break self.request.sendall(self.data.upper()) except Exception as e: print(self.client_address,"连接断开") finally: self.request.close() def setup(self): print("before handle,连接建立:",self.client_address) def finish(self): print("finish run after handle") if __name__=="__main__": HOST,PORT = "localhost",9999 server=socketserver.TCPServer((HOST,PORT),MyTCPHandler) server.serve_forever()
import socket client=socket.socket() client.connect(('localhost',9999)) while True: cmd=input("(quit退出)>>").strip() if len(cmd)==0: continue if cmd=="quit": break client.send(cmd.encode()) cmd_res=client.recv(1024) print(cmd_res.decode()) client.close()
多线程:ThreadingTCPServer
多进程:ForkingTCPServer(Unix)
多线程版:
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): try: while True: self.data=self.request.recv(1024) print("{} send:".format(self.client_address),self.data) if not self.data: print("connection lost") break self.request.sendall(self.data.upper()) except Exception as e: print(self.client_address,"连接断开") finally: self.request.close() def setup(self): print("before handle,连接建立:",self.client_address) def finish(self): print("finish run after handle") HOST,PORT = "localhost",9999 server=socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)#多线程版 server.serve_forever()
以上就是关于如何使用python中socketserver的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。