socket实现文件传输

时间:2021-11-12 03:42:41
server:
===========================================
import socket
import struct
import json
sk = socket.socket()
sk.bind(('127.0.0.1',8989))
sk.listen() conn,addr = sk.accept() resv_size = conn.recv(4) #会儿收到报头的大小,经过struct转码的字节码
dic_size = struct.unpack('i',resv_size)[0] # 对字节码转码,得到报头的大小
bytes_head = conn.recv(dic_size) # 接收bytes类型的报头
head = json.loads(bytes_head.decode('utf-8')) # 真正的报头
filesize = head['filesize'] # 传输文件大小
buffer = 1024
with open(head['filename'],'wb') as f:
while True:
if filesize >= buffer:
content = conn.recv(buffer)
# 打开文件,写入本地
f.write(content)
filesize -= buffer
else:
content = conn.recv(filesize)
# 打开文件,写入本地
f.write(content)
break
conn.close()
sk.close() ===============================================================================
client
==================================================================
import socket
import os
import struct
import json
sk = socket.socket()
sk.connect(('127.0.0.1',8989))
dic = {'filepath':r'E:\常用软件\pandownload\pan下载数据\day32',
'filesize':None,
'filename':'04 python fullstack s9day32 struct模块补充.mp4'}
path = os.path.join(dic['filepath'],dic['filename'])
dic_size = os.path.getsize(path)
dic['filesize'] = dic_size
dic_json = json.dumps(dic) #字典转成字符串
# print(dic['filesize'])
bytes_head = dic_json.encode('utf-8')
send_size = struct.pack('i',len(bytes_head))
sk.send(send_size)
sk.send(bytes_head)
buffer = 1024
with open(path,'rb') as f:
while dic_size:
if dic_size >= buffer:
content = f.read(buffer)
sk.send(content)
dic_size -= buffer
else:
content = f.read(dic_size)
sk.send(content) break sk.close()