day35 作业

服务端

import subprocess
import struct
import json
from socket import *

server = socket(AF_INET, SOCK_STREAM)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(('0.0.0.0',8899))
server.listen(5)

while True:
conn, client_addr = server.accept()

while True:
    try:
        cmd = conn.recv(1024)
        if len(cmd) == 0: break
        obj = subprocess.Popen(cmd.decode('utf-8'),
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE
                               )

        stdout_res = obj.stdout.read()
        stderr_res = obj.stderr.read()
        total_size = len(stdout_res) + len(stderr_res)

        # 1、制作头
        header_dic = {
            "filename": "a.txt",
            "total_size": total_size,
            "md5": "123123xi12ix12"
        }

        json_str = json.dumps(header_dic)
        json_str_bytes = json_str.encode('utf-8')

        # 2、先把头的长度发过去
        x = struct.pack('i', len(json_str_bytes))
        conn.send(x)

        # 3、发头信息
        conn.send(json_str_bytes)
        # 4、再发真实的数据
        conn.send(stdout_res)
        conn.send(stderr_res)

    except Exception:
        break
conn.close()

客户端

import struct
import json
from socket import *

client=socket(AF_INET,SOCK_STREAM)
client.connect(('121.36.98.49',8899))

while True:
    cmd=input('请输入命令>>:').strip()
    if len(cmd) == 0:continue
    client.send(cmd.encode('utf-8'))

    # 接收端
    # 1、先手4个字节,从中提取接下来要收的头的长度
    x=client.recv(4)
    header_len=struct.unpack('i',x)[0]

    # 2、接收头,并解析
    json_str_bytes=client.recv(header_len)
    json_str=json_str_bytes.decode('utf-8')
    header_dic=json.loads(json_str)
    print(header_dic)
    total_size=header_dic["total_size"]

    # 3、接收真实的数据
    recv_size = 0
    while recv_size < total_size:
        recv_data=client.recv(1024)
        recv_size+=len(recv_data)
        print(recv_data.decode('gbk'),end='')
    else:
        print()

来源:https://www.cnblogs.com/hz2lxt/p/12747578.html