python - socketserver 模塊應用
阿新 • • 發佈:2018-10-05
print while serve nbsp unp reading rip exce continue
server端:
import socketserver import subprocess import json import struct class MyTCPHandler(socketserver.BaseRequestHandler): print("執行程序") def handle(self): #所有請求的交互都是在handle裏執行的, while True: try: # 獲取指令 self.data = self.request.recv(1024).strip() zl_s= self.data.decode() # 指令執行返回數據 data = subprocess.Popen(zl_s, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) data_Y_b = data.stdout.read() data_E_b = data.stderr.read() # 封裝數據總長度 data_len = len(data_Y_b) + len(data_E_b) data_dict= {"data_dict": data_len} json_data_s = json.dumps(data_dict) # 封裝head部長度 json_data_b = json_data_s.encode() head_len_i = len(json_data_b) # 封裝前4個字節長度 head_len_b = struct.pack("i", head_len_i)# 發送4個字節,發送head,發送數據 self.request.sendall(head_len_b) self.request.sendall(json_data_b) self.request.sendall(data_Y_b) self.request.sendall(data_E_b) except ConnectionResetError as e: print("err ",e) break if __name__ == "__main__": HOST, PORT = "127.0.0.1", 8080 server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) #線程 server.serve_forever()
client端:
import socket import json import struct ip = "127.0.0.1" port = 8080 ip_port = (ip,port) buffer_size = 1024 client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_socket.connect(ip_port) while True: #發送指令至服務端. zhiling_s = input(">>>:").strip() if not zhiling_s:continue zhiling_b = zhiling_s.encode() client_socket.send(zhiling_b) #層層封裝,收取對應數據對應長度,解封裝. #獲取前四個字節長度 head_len_b = client_socket.recv(4) head_len_i = struct.unpack(‘i‘,head_len_b)[0] print(head_len_i) #獲取head部長度 json_data_b = client_socket.recv(head_len_i) print(len(json_data_b)) #獲取數據總長度 json_data_s = json_data_b.decode() data_dict = json.loads(json_data_s) data_len = data_dict["data_dict"] print(data_len) #循環收取總數據 data_len_recv = 0 data = b"" while data_len_recv < data_len: data += client_socket.recv(buffer_size) data_len_recv += len(data) print(data.decode("gbk")) client_socket.close()
python - socketserver 模塊應用