前面的幾個例子都是單線程的,下面再來講說多線程的。
python
1.多線程模塊服務器
主要是socketserver模塊,以下圖示:多線程
2.多線程原理併發
以下圖示說明:
socket
3.SockteServer例子說明ide
服務器端:
函數
客戶端:spa
4.演示線程
仍是之前面例子,對代碼進行修改,做以下的演示。
3d
Server端:
import SocketServer #導入SocketServer,多線程併發由此類實現 class MySockServer(SocketServer.BaseRequestHandler): #定義一個類 def handle(self): #handle(self)方法是必需要定義的,能夠看上面的說明 print 'Got a new connection from', self.client_address while True: data = self.request.recv(1024) #須要經過self的方法調用數據接收函數 if not data:break print 'recv:', data self.request.send(data.upper()) #須要經過self的方法調用數據接收函數 if __name__ == '__main__': #並不是必定要用這樣的方式,只是建議這樣使用 HOST = '' #定義偵聽本地地址口(多個IP地址狀況下),這裏表示偵聽全部 PORT = 50007 #Server端開放的服務端口 s = SocketServer.ThreadingTCPServer((HOST, PORT), MySockServer) #調用SocketServer模塊的多線程併發函數 s.serve_forever() #持續接受客戶端的鏈接
Client端:
import socket HOST = '192.168.1.13' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while True: user_input = raw_input('msg to send:').strip() s.sendall(user_input) data = s.recv(1024) print 'Received', repr(data) s.close()
演示:
步驟1:Server端運行服務端程序
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py ===>光標在此到處於等待狀態
步驟2:Client A端運行客戶端程序
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python client4.py msg to send:Hello! ===>User輸入數據 Received 'HELLO!' ===>Server端返回的數據 msg to send:I'm Client A. Received "I'M CLIENT A." msg to send: ===>繼續等待User輸入數據
步驟3:在Server端中觀察現象
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py Got a new connection from ('192.168.1.13', 52650) recv: Hello! recv: I'm Client A. ===>接收到Client A端發送的數據 ===>光標在此到處於等待狀態步驟4:Client B端運行客戶端程序
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python client4.py msg to send:I'm Client B. ===>User輸入數據 Received "I'M CLIENT B." ===>Server端返回的數據 msg to send: ===>繼續等待User輸入數據
步驟5:在Server端中觀察現象
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py Got a new connection from ('192.168.1.13', 52650) recv: Hello! recv: I'm Client A. Got a new connection from ('192.168.1.13', 52651) recv: I'm Client B. ===>接收到Client A端發送的數據 ===>光標在此到處於等待狀態
經過上面的演示,使用SocketServer即可以實現Python Socket的多線程併發。