基于TCP协议传输文件
'''
版本一:
此版本一次写入整个文件大小,
只能传输小文件,大文件可能会传不全
'''
#server端----------------------------------------------
import socket
import json
sk = socket.socket()
sk.bind(('127.0.0.1',9001))
sk.listen()
con,addr = sk.accept()
msg = con.recv(1024).decode('utf-8')
dic = json.loads(msg)
with open(dic['filename'],mode='wb') as f :
content = con.recv(dic['filesize'])
print('--->',len(content))
f.write(content)
con.close()
sk.close()
#client端————————————————————————————————————————————————
import os
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
#获取文件名|文件小
abs_path = r'D:\Wang.YH\Videos\人民至上.mp4'
filename = os.path.basename(abs_path)
filesize = os.path.getsize(abs_path)
dic = {'filename':filename,
'filesize':filesize}
str_dic = json.dumps(dic)
sk.send(str_dic.encode('utf-8'))
with open(abs_path,mode='rb') as f:
content = f.read()
sk.send(content)
sk.close()
'''
版本二:
分次传输文件
不足:可能会产生粘包现象
'''
#serfer端——————————————————————————————————————
import socket
import json
sk = socket.socket()
sk.bind(('127.0.0.1',9001))
sk.listen()
con,addr = sk.accept()
msg = con.recv(1024).decode('utf-8')
dic = json.loads(msg)
with open(dic['filename'],mode='wb') as f:
while dic['filesize'] >0:
content = con.recv(1024)
dic['filesize'] -=len(content)
f.write(content)
con.close()
sk.close()
#client端————————————————————————————————————————————————
import os
import socket
import json
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
#获取文件名|文件小
abs_path = r'D:\Wang.YH\Videos\人民至上.mp4'
filename = os.path.basename(abs_path)
filesize = os.path.getsize(abs_path)
dic = {'filename':filename,
'filesize':filesize}
str_dic = json.dumps(dic)
sk.send(str_dic.encode('utf-8'))
with open(abs_path,mode='rb') as f:
while filesize >0:
content = f.read(1024)
filesize -= len(content)
sk.send(content)
sk.close()
'''
版本三:
解决粘包
'''
#server端————————————————————————————————————————
import socket
import json
import struct
sk = socket.socket()
sk.bind(('127.0.0.1',9001))
sk.listen()
con,addr = sk.accept()
msg_len = con.recv(4)
dic_len = struct.unpack('i',msg_len)[0]
msg = con.recv(dic_len).decode('utf-8')
dic = json.loads(msg)
with open(dic['filename'],mode='wb') as f:
while dic['filesize'] >0:
content = con.recv(1024)
dic['filesize'] -=len(content)
f.write(content)
con.close()
sk.close()
#client端——————————————————————————————————
import os
import socket
import json
import struct
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
#获取文件名|文件小
abs_path = r'D:\Wang.YH\Videos\人民至上.mp4'
filename = os.path.basename(abs_path)
filesize = os.path.getsize(abs_path)
dic = {'filename':filename,
'filesize':filesize}
str_dic = json.dumps(dic)
b_dic = str_dic.encode('utf-8')
mlen = struct.pack('i',len(b_dic))
sk.send(mlen)
sk.send(b_dic)
with open(abs_path,mode='rb') as f:
while filesize >0:
content = f.read(1024)
filesize -= len(content)
sk.send(content)
sk.close()