python--簡單的文件斷點續傳實例

1、程序說明python

 

一、文件上傳目標路徑:home/file正則表達式

二、目標文件:putfile.png服務器

三、服務端代碼:put_server.pysocket

四、客戶端代碼:put_client.py函數

 

2、各部分代碼post

一、服務端代碼:put_server.pyspa

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 """
 4 實現文件斷點續傳的服務器端
 5 """
 6 
 7 import socket
 8 import os
 9 
10 BASE_DIR = os.path.dirname(os.path.dirname(__file__))
11 
12 home = os.path.join(BASE_DIR, "home/file")
13 sk = socket.socket()
14 sk.bind(('127.0.0.1', 8001))
15 sk.listen(5)
16 
17 while True:
18     print("Waiting....")
19     conn, addr = sk.accept()
20     conn.sendall(bytes('歡迎登陸', encoding='utf-8'))
21     flag = True
22     while flag:
23         client_bytes = conn.recv(1024)   #接收客戶端發送過來的內容
24         client_str = str(client_bytes, encoding='utf-8')  #將內容轉換成字符串
25 
26         # 將客戶端發送過來的內容以"|"拆分爲:命名方法,文件名,文件大小,目標路徑
27         func, file_name, file_byte_size, targe_path = client_str.split('|', 3)
28         file_byte_size = int(file_byte_size)
29         path = os.path.join(home, file_name)
30         has_received = 0
31 
32         #首先判斷該路徑下是否已存在文件
33         if os.path.exists(path):
34             conn.sendall(bytes("2003", encoding='utf-8'))  #發送通知客戶端,該文件已存在
35             is_continue = str(conn.recv(1024), encoding='utf-8')  #等待客戶端選擇回覆
36             if is_continue == "2004":
37                 has_file_size = os.stat(path).st_size
38                 conn.sendall(bytes(str(has_file_size), encoding='utf-8'))  #將已接收的文件大小給客戶端
39                 has_received += has_file_size
40                 f = open(path, 'ab')
41             else:
42                 f = open(path, 'wb')
43         else:
44             conn.sendall(bytes("2002", encoding='utf-8'))
45             f = open(path, 'wb')
46 
47         while has_received < file_byte_size:
48             try:
49                 data = conn.recv(1024)
50                 if not data:
51                     raise Exception
52             except Exception:
53                 flag = False
54                 break
55             f.write(data)
56             has_received += len(data)
57         print("文件已接收完成!")
58         f.close()

 

二、客戶端代碼:put_client.py指針

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 """
 4 實現文件斷點續傳的客戶端
 5 """
 6 
 7 import socket
 8 import sys
 9 import re
10 import os
11 FILE_DIR = os.path.dirname(__file__)
12 
13 ck = socket.socket()
14 ck.connect(('127.0.0.1', 8001))
15 print(str(ck.recv(1024), encoding='utf-8'))
16 
17 
18 #定義一個函數,計算進度條
19 def bar(num = 1, sum = 100):
20     rate = float(num) / float(sum)
21     rate_num = int(rate * 100)
22     temp = '\r%d %%' % (rate_num)
23     sys.stdout.write(temp)
24 
25 while True:
26     inp = input('請輸入(內容格式:post|文件路徑 目標路徑): \n >>> ').strip()  #輸入內容格式:命令|文件路徑 目標路徑
27     func, file_path =inp.split("|", 1)  #將輸入的內容拆分爲兩部分,方法名和路徑
28     local_path, target_path = re.split("\s*", file_path, 1) #再將路徑部分,經過正則表達式。以空格拆分爲:文件路徑和上傳的目標路徑
29     file_byte_size = os.stat(local_path).st_size  #獲取文件的大小
30     file_name = os.path.basename(local_path)   #設置文件名
31 
32     post_info = "post|%s|%s|%s" % (file_name, file_byte_size, target_path)  #將發送的內容進行拼接
33     ck.sendall(bytes(post_info, encoding='utf-8'))  #向服務器端發送內容
34 
35     result_exist = str(ck.recv(1024), encoding='utf-8')
36     has_sent = 0
37     if result_exist == "2003":
38         inp = input("文件已存在,是否續傳?Y/N:").strip()
39         if inp.upper() == 'Y':
40             ck.sendall(bytes("2004", encoding='utf-8'))
41             result_continue_pos = str(ck.recv(1024), encoding='utf-8')  #已經傳輸了多少的文件內容
42             print(result_continue_pos)
43             has_sent = int(result_continue_pos)
44 
45         else:
46             ck.sendall(bytes("2005", encoding='utf-8'))  #發送2005表明不續傳
47 
48     file_obj = open(local_path, 'rb')  #對文件進行讀操做
49     file_obj.seek(has_sent)  #調整指針
50 
51     while has_sent < file_byte_size:
52         data = file_obj.read(1024)
53         ck.sendall(data)
54         has_sent += len(data)
55         bar(has_sent, file_byte_size)  #進度條
56 
57     file_obj.close()
58     print("文件上傳成功!")
相關文章
相關標籤/搜索