服务端:
import socketimport subprocessimport structimport json#买手机server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#print(phone)#绑定手server.bind((‘192.168.0.102‘, 8080))server.listen(5)while True: conn, cent = server.accept() while True: try: cmd = conn.recv(1024) 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 = {‘md5‘:‘ssssss‘, ‘filename‘:‘a.txt‘, ‘total_saze‘:len(stdout)+len(stderr)} head_json = json.dumps(header_dic) head_bytes = head_json.encode(‘utf-8‘) #第二部发送报头长度 conn.send(struct.pack(‘i‘, len(head_bytes))) # total_saze = len(stdout)+len(stderr) # header = struct.pack(‘i‘, total_saze) #第三步发送报头 conn.send(head_bytes) #第四步发送真是数据 conn.send(stdout+stderr) except ConnectionResetError: break conn.close()server.close() 客户端:
import socketimport structimport json#买手机client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#拨号client.connect((‘192.168.0.102‘, 8080))while True: cmd = input(‘请输入你的指令>>>‘) client.send(cmd.encode(‘utf-8‘)) # 第一步接收报头长度 obj = client.recv(4) head_saze = struct.unpack(‘i‘, obj)[0] #header = client.recv(4) #第二步再收报头 head_bytes = client.recv(head_saze) # 第三步从报头中解释出报头包含的所有信息 head_json = head_bytes.decode(‘utf-8‘) head_dic = json.loads(head_json) print(head_dic) total_saze = head_dic[‘total_saze‘] print(total_saze) # 第四步接收真实数据 recv_save = 0 data_recv = b‘‘ while recv_save < total_saze: res = client.recv(1024) data_recv+=res recv_save+=len(res) #data = client.recv(1024) print(len(data_recv.decode(‘GBK‘)),‘\n‘,data_recv.decode(‘GBK‘))client.close()
原文地址:https://www.cnblogs.com/yuexijun/p/11480099.html
时间: 2024-10-19 18:49:57