# 客户端 # -*- coding: utf-8 -*- import socketserver import struct import json import subprocess class MyTcpHandler(socketserver.BaseRequestHandler): def handle(self): while True: try: cmd = self.request.recv(1024) if not cmd: break print(cmd.decode('utf-8')) obj = subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout = obj.stdout.read() stderr = obj.stderr.read() # 制作报头 header_dic = { 'file_name': cmd.decode('utf-8'), 'data_size': len(stdout) + len(stderr) } header_json = json.dumps(header_dic) header_bytes = header_json.encode('utf-8') # 发送报头字典长度 self.request.send(struct.pack('i', len(header_bytes))) # 发送报头 self.request.send(header_bytes) # 发送正文 self.request.send(stdout + stderr) except ConnectionResetError: break if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyTcpHandler) server.serve_forever()
# 服务端 # -*- coding: utf-8 -*- from socket import * import struct import json client = socket(AF_INET, SOCK_STREAM) client.connect(('127.0.0.1', 8080)) while True: cmd = input('>>>:').strip() if not cmd: continue client.send(cmd.encode('utf-8')) # 先接收报头长度并解析 dic_size = client.recv(4) header_size = struct.unpack('i', dic_size)[0] # 获取报头字典 header_json = client.recv(header_size).decode('utf-8') header_dic = json.loads(header_json) file_size = header_dic['data_size'] get_size = 0 info = b'' while get_size < file_size: data = client.recv(1024) get_size += len(data) info += data print(info.decode('gbk'))