python之多並發socket(zz)
阿新 • • 發佈:2017-09-22
請求 mixin reading odin read 處理 exceptio col recv
本文轉載自:http://www.cnblogs.com/bainianminguo/p/7337210.html
先看socket多並發的服務端的代碼,這裏是用多線程實現的多並發socketserver
import socketserver # socketserver有四個基本的類,後兩個不常用,這4個類處理並發請求都是同步的,他們其實不是多線程的, # 他們只是把socke封裝了一下,加了一些方法,這裏還沒有實現多並發和多線程 # 這些方法不適用每個請求都耗費長時間才能完成 # socketserver.TCPServer # socketserver.UDPServer # socketserver.UnixStreamServer# socketserver.UnixDatagramServer # socketserver.ForkingMixIn # socketserver.ThreadingMixIn # ======================================================================================================== # 我們真正要用的下面這4個方法 # 多進程的socketserver # socketserver.ForkingTCPServer # socketserver.ForkingUDPServer# 多進程的socketserver # socketserver.ThreadingTCPServer # socketserver.ThreadingUDPServer # ======================================================================================================== class MyTcpServerClass(socketserver.BaseRequestHandler): def handle(self): print("waiting for new connect:") print("new client :",self.client_address) while True: try: data=self.request.recv(1024) print("the client:",self.client_address,str(data,encoding=‘utf-8‘)) except Exception: print("the client [%s] is unconnected!"%(self.client_address[1])) self.request.close() break if __name__==‘__main__‘: ipbind=(‘127.0.0.1‘,2345) server=socketserver.ThreadingTCPServer(ipbind,MyTcpServerClass) server.serve_forever()
然後看下客戶端的代碼:
import socket ipbind=(‘127.0.0.1‘,2345) c=socket.socket() c.connect(ipbind) while True: c_input=input("客戶端:") c.send(bytes(c_input,encoding=‘utf-8‘)) s_send=c.recv(1024) print("服務端:",str(s_send,encoding=‘utf-8‘))
python之多並發socket(zz)