本例中以client作为发送端
server作为接收端
#server
import socket
import json
import struct
import os
sk = socket.socket()
#避免服务器重启时候报address already in use
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bind(('127.0.0.1',8080))
sk.listen()
con, addr = sk.accept()
buffer = 4096
head_len = con.recv(4)
head_len = struct.unpack('i', head_len)[0]
json_head = con.recv(head_len).decode('utf-8)
head = json.loads(json_head)
filesize = head['filesize']
with open(head['filename'], 'wb') as f:
while filesize:
if filesize >= buffer:
content = conn.recv(buffer)
f.write(content)
filesize -= buffer
else:
content = conn.recv(filesize)
f.write(content)
break
con.close()
sk.close()
#client
import socket
import json
import struct
import os
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
#订制报头
head = {'filepath' : r'your path',
'filename' : r'your name',
'filesize' : None}
#buffer为一次传文件的大小
buffer = 4096
filepath = os.path.join(head['filepath'], head['filename'])
filesize = os.path.getsize(filepath)
head['filesize'] = filesize
#将字典转化为字符串
json_head = json.dumps(head)
bytes_head = json_head.encode('utf-8')
head_len = len(bytes_head)
pack_len = struct('i',head_len)
sk.send(pack_len)
sk.send(bytes_head)
with open(filepath, 'rb') as f:
while filesize:
if buffer <= filesize:
content = f.read(buffer)
sk.send(content)
filesize -= buffer
else
sk.send(bytes(filesize))
break
sk.close()