Python_day6:socket網路程式設計
阿新 • • 發佈:2018-11-01
一、socket
socket即套接字,用於描述IP地址和埠,是一個通訊鏈的控制代碼,應用程式通常通過"套接字"向網路發出請求或者應答網路請求。
最簡單的socket,一次
1 import socket 2 server = socket.socket() #獲得例項 3 server.bind(("localhost",9999)) #繫結主機和埠以元組形式 4 server.listen() #監聽 5 print("等待客戶端連線。。") 6 conn,addr = server.accept() #接收連線 7 data = conn.recv(1024) #server接收資料,預設最大為8192 8 print("收到:",data.decode()) #data是byte格式要decode一下 9 conn.send("不要回答!不要回答!不要回答!".encode())#傳送的資料要是byte格式 10 server.close()
1 import socket 2 client = socket.socket() 3 client.connect(("localhost",9999)) 4 client.send("請佔領地球!".encode("utf-8")) 5 data = client.recv(1024)client6 print("反饋:",data.decode()) 7 client.close()
實現多次互動,多連線處理,加兩個迴圈
1 import socket 2 server = socket.socket() 3 server.bind(("localhost",9999)) 4 server.listen() 5 while True: #第一層迴圈 6 print("等待客戶端連線。。") 7 conn,addr = server.accept() 8 while True: #第二層迴圈server9 data = conn.recv(1024) 10 if not data: #如果沒有資料就斷開 11 print("客戶端斷開。") 12 break 13 print("收到:",data.decode()) 14 conn.send("不要回答!不要回答!不要回答!".encode()) 15 server.close()
1 import socket 2 client = socket.socket() 3 client.connect(("localhost",9999)) 4 while True: 5 msg = input(">>:").strip() 6 if len(msg) == 0:continue 7 client.send(msg.encode("utf-8")) 8 data = client.recv(1024) 9 print("反饋:",data.decode()) 10 client.close()client
防止黏包在兩次send之間要加個客戶端響應
1 conn.send(str(len(res)).encode()) 2 client_ack = conn.recv(1024) 3 conn.sendall(res)server黏包
二、socketserver
1 import socketserver 2 3 class MyTCPHandler(socketserver.BaseRequestHandler): 4 """ 5 The request handler class for our server. 6 It is instantiated once per connection to the server, and must 7 override the handle() method to implement communication to the client. 8 """ 9 10 def handle(self): 11 # self.request is the TCP socket connected to the client 12 self.data = self.request.recv(1024).strip() 13 print("{} wrote:".format(self.client_address[0])) 14 print(self.data) 15 # just send back the same data, but upper-cased 16 self.request.sendall(self.data()) 17 18 if __name__ == "__main__": 19 HOST, PORT = "localhost", 9999 20 21 # Create the server, binding to localhost on port 9999 22 server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) 23 #server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) #多併發 24 # Activate the server; this will keep running until you 25 # interrupt the program with Ctrl-C 26 server.serve_forever()socketserver