【Python】文件传输

def run_cmd(connter, cmd):
obj = subprocess.Popen(cmd.decode('utf-8'),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)

total_size = len(obj.stdout.read()) + len(obj.stderr.read())
header_dict = {
'filename': 'a.txt',
'md5': 'xxdxxx',
'total_size': total_size
}
header_json = json.dumps(header_dict).encode('uft-8')

# 第二步:制作 报头 的长度,并发送
header_len = struct.pack('i', len(header_json)) # i模式为int, l模式为long
connter.send(header_len)

# 第三步:把 报头 发送给客户端
connect.send(header_json)

# 第四步:发送真实数据
connect.send(obj.stdout.read())
connect.send(obj.stderr.read())


def get_cmd(connter):
# 第一步 :收到报头长度
obj = connter.recv(4)
header_len = struct.unpack('i', obj)[0]

# 第二步 :收报头
header = phone.recv(header_len)

# 第三步:从报头取出信息
header_json = header.decode('uft-8')
header_dict = json.loads(header_json)
total_size = header_dict['total_zize']

# 第四步:接收真实的数据
recv_size = 0
recv_data = b''
while recv_size < total_size:
res = phone.recv(1024)
recv_data += res
recv_size += len(res)

print(recv_data.decode('utf-8'))


# 客户端
import socket
import struct
import os
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080))

while 1:
cmd = input()
phone.send(cmd.encode('utf-8'))
if not cmd:
continue

if cmd[0] == 'get':
get(phone)
elif cmd[0] == 'disconnect':
phone.close()
break
else:
get_cmd(phone)


# 服务端
import socket
import subprocess
import json
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
phone.bind(('127.0.0.1', 8080))
phone.listen(5)

while 1:
connect, client_addr = phone.accept()
while 1:
try:
cmd = connect.recv(1024)
if not cmd:
break
cmds = cmd.decode('utf-8').split()
if cmds[0] == 'get':
filename = cmds[1]
up_load(connect, filename)
elif cmds[0] == 'disconnect':
connect.close()
phone.close()
break
else:
run_cmd(connect, cmds)
except ConnectionResetError:
connect.close()
break
posted @ 2018-08-26 13:43  caya  阅读(141)  评论(0编辑  收藏  举报