Server-side configuration:
Importsocket,subprocess,struct fromSocketImport*Server=socket (Af_inet,sock_stream) server.bind (('127.0.0.1', 8080)) Server.listen (5) whiletrue:conn,client_addr=server.accept () whileTrue:Try: cmd=CONN.RECV (1024) ifLen (cmd) = = 0: Breakobj=subprocess. Popen (Cmd.decode ('Utf-8'), Shell=True, stdout=subprocess. PIPE, stderr=subprocess. PIPE,) out=obj.stdout.read ()#bytes TypeErr=Obj.stderr.read ()Print(Len (out+err)) #steps to solve the sticky pack problem, the length of the first hairstyle dataTotal_size=len (out) +len (ERR)#data type, 1. Change to bytes Type 2. Still a fixed length. #1. Make a fixed length of BaotouHeader=struct.pack ('I', Total_size)#2. Send Headersconn.send (header)#The size of the head header of a fixed datagram (custom data) #Here's what the real data is sent #conn.send (Out+err) #2 packages are sent together in the past because of the short intervalConn.send (out) conn.send (err)#the whole of sending past is a datagram = header + Data section exceptConnectionreseterror: Breakconn.close () server.close ( )
Client Side configuration:
ImportSocketImportsocket,structclient=Socket.socket (Socket.af_inet,socket. Sock_stream) Client.connect (('127.0.0.1', 8080)) whileTrue:cmd=input ('Enter the command to execute:') ifLen (cmd) = = 0:Continueclient.send (Cmd.encode ('Utf-8')) #1. The default stuck of the fixed-length header is fixed with a length of 4HEADER=CLIENT.RECV (4)#The second collection is not the next Baotou, it's the residue of the last order. #2. Parsing BaotouTotal_size=struct.unpack ('I', header) [0]#It's a ganso, and 0 of that is the length value. Print(total_size)#3. According to the information in Baotou, collect real data #Client.recv (total_size) because the amount of real data is too large, so consider the while loop #think if the data is large, total_size data will be very large will be directly error #in order to solve the large input program, define a small variable, loop a little bit to collectRecv_size=0 Res=b"' whileRecv_size <Total_size:recv_data=CLIENT.RECV (1024)#recv_data is the bytes type, is the only real value, how much will be collectedres+=Recv_data recv_size+=Len (recv_data)Print(Res.decode ('GBK') ) Client.close ()
Python Socket Sticky Pack problem