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()