服务端
1 from socket import *
2 import subprocess,json,struct
3
4 server= socket(AF_INET,SOCK_STREAM)
5 server.bind(('127.0.0.1',8081))
6 server.listen(5)
7
8 while True:
9 client,client_addr=server.accept()
10 while True:
11 try:
12 cmd=client.recv(1024).decode('utf-8')
13 if not cmd:break
14 # 执行命令
15 obj=subprocess.Popen(cmd,
16 shell=True,
17 stdout=subprocess.PIPE,
18 stderr=subprocess.PIPE
19 )
20 # 显示正确和错误信息
21 stdout=obj.stdout.read()
22 stderr=obj.stderr.read()
23 print('执行结果长为%s' %(len(stdout)+len(stderr)))
24 # 制定报头
25 head_dic={'filename':'a.txt',
26 'md5':'rdgdgfdgfdgd',
27 'size':len(stdout)+len(stderr)
28 }
29 head_json=json.dumps(head_dic)
30 head_bytes=head_json.encode('utf-8')
31 # 发送报头长度
32 head_len=len(head_bytes)
33 head_len_bytes = struct.pack('i', head_len)
34 client.send(head_len_bytes)
35 # 发送报头
36 client.send(head_bytes)
37 # 发送真实数据
38 client.send(stdout)
39 client.send(stderr)
40 except ConnectionResetError:
41 print('客户端异常关闭')
42 break
43 client.close()
44
45 server.close()
客户端
1 from socket import *
2 import json,struct
3
4 client= socket(AF_INET,SOCK_STREAM)
5 client.connect(('127.0.0.1',8081))
6
7 while True:
8 cmd=input('>>>').strip()
9 if not cmd:continue
10 client.send(cmd.encode('utf-8'))
11 # 先接受报头长度
12 head_len=struct.unpack('i',client.recv(4))[0]
13 # 接收报头
14 head_bytes=client.recv(head_len)
15 # 解析报头
16 head_json=head_bytes.decode('utf-8')
17 head_dic=json.loads(head_json)
18 print(head_json)
19 total_size=head_dic['size']
20 # 取出真实数据
21 recv_size=0
22 finnally_data=b''
23 while total_size>recv_size:
24 recv_data=client.recv(1024)
25 finnally_data+=recv_data
26 recv_size+=len(recv_data)
27 print(finnally_data.decode('gbk'))
28
29 client.close()