python_ network programming struct module package to solve the sticky problem

struct module:

  Function: a can type, such as numbers, conversion to a fixed length of bytes.

Import struct 

RET = struct.pack ( ' I ' , 456 872 783)      # 'I' representatives int, is about to make a total number into fixed length (4 bytes) bystes type 
Print (RET) 

NUM = struct.unpack ( ' I ' , RET)     # conversion back, returns a tuple 
Print (NUM [0])    # advance tuples worth to 4096

Package to solve the sticky problem:

  Server:

Import struct
 Import Socket 
SK = socket.socket () 
sk.bind (( ' 127.0.0.1 ' , 8080 )) 
sk.listen () 
Conn, addr = sk.accept ()
 the while True: 
    cmd = INPUT ( ' >>> ' )
     iF cmd == ' Q ' :       # when the input' q ', the end, and the client sends a' q '. 
        conn.send (B ' Q ' )
         BREAK 
    conn.send (cmd.encode ( ' GBK ' ))     #Cmd command input to the client 
    NUM = conn.recv (. 4)       # of bytes received information (message length information is returned). 
    struct.unpack = NUM ( ' I ' , NUM) [0]      # of the received bytecode into the original type and placed inside a tuple, followed by adding [0] in advance the value of the tuple. 
    conn.recv = RES (int (num)). decode ( ' GBK ' )      # length of the received message num. 
    Print (RES)       # print 
conn.Close () 
sk.close ()

  Client:

Import struct
 Import Socket
 Import The subprocess 

SK = socket.socket () 
sk.connect (( ' 127.0.0.1 ' , 8080 ))
 the while True: 
    cmd = sk.recv (1024) .decode ( ' GBK ' )    # transmit and receive server the cmd command to 
    iF cmd == ' Q ' :   # upon receiving the 'q', end. 
        BREAK 
    # client cmd command received by the end of the execution. And the right messages and error messages were placed stdout and stderr pipes. 
    subprocess.Popen = RES (cmd, the shell = True, subprocess.PIPE = stdout, stderr = subprocess.PIPE) 
    std_outRes.stdout.read = ()      # inner conduit read the correct message 
    std_err res.stderr.read = ()      # read error message pipeline 
    len_num = len (std_out) + len (std_err)      # calculate and correct the error message the total length 
    num_by struct.pack = ( ' I ' , len_num)        # the total length of the message converted to a length of 4 bytes of code 
    sk.send (num_by)      # send message length information 
    sk.send (std_out)     # send the correct message 
    sk.send (std_err)      # sends an error message 

sk.close ()

 

Guess you like

Origin www.cnblogs.com/wangdianchao/p/11698977.html