socket實現文件傳輸


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()










免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM