Server----------------------
#!/usr/bin/env python
# Encoding:utf-8
# DATE:2018/6/5
Import socket
Import subprocess
Import struct
Phone = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Phone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)
Phone.bind (' 127.0.0.1 ', 8081)
Phone.listen (5)
Print (' Starting ... ')
While True: # link loop, ensure client stops, service side does not stop, but concurrency is not supported
conn, client_addr = Phone.accept ()
Print (CLIENT_ADDR)
While True:
Try: # Window Exception capture
# 1 Receive commands
cmd = CONN.RECV (1024)
If not cmd: # for Linux
Break # Client dropped, send empty
Print (' Client's data ', CMD)
# 2 Execute command, get results
obj = subprocess. Popen (Cmd.decode (' Utf-8 '), Shell=true,
stdout = subprocess. PIPE,
stderr = subprocess. PIPE)
stdout = Obj.stdout.read ()
stderr = Obj.stderr.read ()
# 3 Returns the result of the command to the client
# First step: Make a fixed-length header
Total_size = Len (stdout) + len (stderr)
Header = Struct.pack (' i ', total_size)
# Step two, send the datagram to the client
Conn.send (header)
# # print (len (stdout) + len (stderr))
# total_size = Len (stdout) + len (stderr)
# conn.send (str (total_size). Encode (' Utf-8 '))
# Step three, then send the real data
Conn.send (STDOUT)
Conn.send (stderr)
Except Connectionreseterror:
Break
Conn.close ()
Phone.close ()
Client-------------------
#!/usr/bin/env python
# Encoding:utf-8
# DATE:2018/6/5
Import socket
Import struct
Phone = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Phone.connect (' 127.0.0.1 ', 8081)
While True:
# 1 rounds of orders
cmd = input (' >>>: '). Strip ()
If not cmd:continue
Phone.send (Cmd.encode (' Utf-8 ')) # application issued to operating system, operating system calls network card
# that command results
# First step: Take the header first
Header = PHONE.RECV (4)
# Part Two: Parsing the description of real data from Baotou (length of data)
Total_size = Struct.unpack (' i ', header) [0]
# Step three: Receive real data
Recv_size = 0
Recv_data = B '
While Recv_size < total_size:
res = PHONE.RECV (1024)
Recv_data + = Res
Recv_size + = Len (res)
Print (Res.decode (' Utf-8 '))
Phone.close ()
Solving Sticky pack problems-simple version