服务端:Server
from socket import*
import subprocess,struct,json
server=socket(AF_INTE,SOCK_STREAM)
server.bind(('127.0.0.1',8080))
server.listen(5)
#链接循环
while True:
conn.client_addr=server.accept()
print(client_addr)
#通信循环
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=obj.stdout.read()
stderr=obj.stderr.read()
#1制作报头
header_dic{
'filename':'a.txt',
'md5':'asdfasdf123',
'total_size':len(stdout)+len(stderr) }
header_json=json.dumps(header_dic)
header_bytes=header_json.encode('utf-8)
#2先发送4个bytes(它包含报头的长度)
conn.send(struct.Pack('i',len(header_bytes)))
#3在发送报头
conn.send(header_bytes)
#4再发送正式数据
conn.send(stdout)
conn.send(stderr)
except ConnectionRestEroor:
break
conn.close
server.close
客户端Client
from Socket import*
import struct
import json
Client=socket(AF_INET,SOCK_STREAM)
client.conn(('127.0.0.1',8081))
#循环通信
while True:
cmd=input(''>>:).strip()
if len(cmd)==0:continue
client.send(cmd.encode('utf-8'))
#1先收4Bytes,解出报头的长度
header_size=struct.unpack('i',client.recv(4))[0]
#2接受报头,拿到header_dic
header_bytes=client.recv(head_size)
header_json=header_bytes.decode('utf-8')
header_dic=json.load(header_json)
print(header_dic)
total_size=header_dic['total_size']
cmd_res=b''
recv_size=0
while recv_size<total_size:
data=client.recv(1024)
recv_size+=len(data)
cmd_res=data
print(cmd_res,decode('gbk'))
client.close()