下面是一個發送檔案的函式,傳輸引數是檔案名和socket
生成一個壓縮包,完成壓縮包的發送之后再將生成的壓縮包刪掉。
在發送一些小的檔案(幾十kb)的時候是正常的,如下圖

退出while回圈時會判斷條件為false(正常)
但是在發送2MB以上的檔案,就會這樣

還沒發送完,條件依然是true的時候,就跳出了
而且后面的
print("總共發送了%s個位元組" % send_size)
print("Send:檔案發送成功")
都沒有執行。
為什么在條件還是true的時候,就突然跳出去了呢?
原始碼如下:
def file_send(self, conn, filename):
true_name = filename
filepath = self.host_path_list[filename]
# filepath相當于一個URL
if filename.find('.') != -1:
filename = filename[0:filename.find('.')] + ".zip"
else:
filename = filename + ".zip"
z = zipfile.ZipFile(filename, 'w')
# 新建一個zip物件
if os.path.isdir(filepath):
# 如果查詢的是子檔案夾 就把里面所有的東西壓縮進filename.zip
for d in os.listdir(filepath):
z.write(filepath + os.sep + d, d)
else:
# 找到是檔案 只用壓一個就行了
z.write(filepath, true_name)
z.close()
# 將頭部資訊封裝成json 再編碼成bytes
header_dic = {
'filename': filename,
'file_size': z.infolist()[0].file_size
}
header_json = json.dumps(header_dic)
header_bytes = header_json.encode('utf-8')
# 打包檔案頭
# 把header的長度封裝成元組
conn.send(struct.pack('i', len(header_bytes)))
# 發送頭
conn.send(header_bytes)
total_size = z.infolist()[0].file_size
# 發送資料
with open(filename, 'rb+') as f:
send_size = 0
while send_size <= total_size:
data = f.read(1024)
conn.send(data)
send_size += len(data)
print("已發送了:%s位元組+ %s" % (send_size,(send_size <= total_size)))
print("總共發送了%s個位元組" % send_size)
print("Send:檔案發送成功")
while True:
# 用于洗掉之前生成的壓縮包
try:
os.remove(filename)
break
except:
continue
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/15280.html
標籤:交換及路由技術
上一篇:關于軟路由系統選擇咨詢
