您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了如何使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。