服务端:import socketimport subprocessimport struct#简易版缺点:struct 的数据i需要在4以内,如果发送的数据较大,会超过I,无法发送。因此需要优化#创建套接字server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)server.bind(('192.168.43.177',8093))server.listen(5)while True: conn,addr = server.accept() while True: try: cmd = conn.recv(8086) if not cmd :break obj = subprocess.Popen(cmd.decode('utf-8'),shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout = obj.stdout.read() stderr = obj.stderr.read() #3.把命令的结果返回给客户端 #第一步:制作固定长度的报头 total_size = len(stdout)+len(stderr) header = struct.pack('i',total_size) print(stdout) conn.send(header) #发送具体内容 conn.send(stdout) conn.send(stderr) except ConnectionResetError: break conn.close()server.close()客户端:
import socketimport subprocessimport structserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)server.connect(('192.168.43.177',8093))while True: #1.发命令 cmd = input('>>:').strip() if not cmd :continue server.send(cmd.encode('utf-8')) #2.拿命令的结果,并打印 # 第一步:先收报头 header = server.recv(4) #第二步:从报头中解析出对真实数据描述 total_size = struct.unpack('i',header)[0] #第三步:接收真实数据 recv_size = 0 recv_data = b'' print(total_size) while recv_size < total_size: res = server.recv(1024) recv_data += res recv_size += len(res) print(recv_data.decode('gbk')) # res1= server.recv(1024) # print(res1.decode('gbk'))server.close()
来源:https://www.cnblogs.com/rainbowupdate/p/12255910.html