SOCKET文件传输client
import socket
import struct
import json
from pathlib import Path
share_dir = Path('local')
def get_file(phone, send_data):
phone.send(send_data.encode('utf-8'))
print('request send')
print('A')
obj = phone.recv(4)
try:
header_size = struct.unpack('i', obj)[0]
'''
header_dic = {
'filename': filename,
'file_size': os.path.getsize(filename)
}
'''
header_bytes = phone.recv(header_size)
header_json = header_bytes.decode('utf-8')
header_dic = json.loads(header_json)
total_size = header_dic['file_size']
filename = header_dic['filename']
with open('%s/%s' % (share_dir, filename), 'wb') as f:
recv_size = 0
while recv_size < total_size:
line = phone.recv(1024)
f.write(line)
recv_size += len(line)
print('总大小:%s 已下载:%s' % (total_size, recv_size))
print('download finished')
except Exception as e:
print(e)
def send_file(phone, send_data, cmd):
phone.send(send_data.encode('utf-8'))
print('request send')
filename = cmd[1]
header_dic = {
'filename': filename,
'file_size': (share_dir / filename).stat().st_size
}
header_json = json.dumps(header_dic)
header_bytes = header_json.encode('utf-8')
phone.send(struct.pack('i', len(header_bytes)))
phone.send(header_bytes)
with open((share_dir / filename), 'rb') as f:
for line in f:
phone.send(line)
print("send finished")
def main():
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('xxx.xx.xx.xxx', 443))
while True:
inp = input('>>> ')
send_data = inp.strip()
cmd = inp.split()
print(cmd[0])
if not cmd:
print('pass')
continue
if cmd[0] == 'quit':
break
if cmd[0] == 'get':
get_file(phone, send_data)
if cmd[0] == 'send':
send_file(phone, send_data, cmd)
print('nothing')
phone.close()
if __name__ == '__main__':
main()