Python实现TCP文件传输
废话少说,直接上代码
1 # 发送端 2 import socket,os 3 from struct import pack 4 5 def send_file(file_name,file_socket:socket.socket): 6 try: 7 f = open(file_name,'rb') 8 size = os.path.getsize(file_name) 9 if size < 1024: 10 read_size = 500 11 elif size < 1024*1024 and size >= 1024: 12 read_size = 500*1024 13 else: 14 read_size = 500*1024*1024 15 file_socket.send(pack('q',size)) 16 del size 17 file_socket.recv(1024) 18 while True: 19 data = f.read(read_size) 20 if not data: 21 break 22 file_socket.send(data) 23 f.close() 24 except FileNotFoundError: 25 print(f'没有找到{file_name}') 26 27 if __name__ == '__main__': 28 try: 29 file_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 30 file_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) 31 ip = str(input('请输入接收端IP:')) 32 port = int(input('请输入接收端端口号:')) 33 file_socket.connect((ip,port)) 34 print('连接成功,准备开始传输。。。') 35 path = r'%s' % (input('请输入文件所在文件夹:') + '/') 36 print(file_socket.recv(1024).decode('gbk')) 37 file_name = str(input()) 38 file_socket.send(file_name.encode('gbk')) 39 send_file(path + file_name,file_socket) 40 except ConnectionResetError: 41 print('接收端断开连接')
1 # 接收端 2 import socket,os 3 from time import time 4 from struct import unpack 5 from tqdm import tqdm 6 7 DOWNLOAD_PATH = 'D:/Python文件传输/' # 传输目录 8 9 def download(file_name,file_socket:socket.socket): 10 file_size = unpack('q',file_socket.recv(1024))[0] 11 if file_size < 1024: 12 print(f'文件大小:{file_size} B') 13 elif file_size < 1024*1024 and file_size >= 1024: 14 print(f'文件大小:{file_size/1024} KB') 15 else: 16 print(f'文件大小:{file_size/(1024*1024)} MB') 17 f = open(file_name,'wb') 18 print('开始传输...') 19 download_size = 2048 20 file_socket.send('开始传输'.encode('gbk')) 21 start = time() 22 for i in tqdm(range(int(file_size/download_size) + 1)): 23 data = file_socket.recv(download_size) 24 f.write(data) 25 end = time() 26 f.close() 27 print('传输完成!') 28 print(f'大约耗时{end - start}秒') 29 30 if __name__ == '__main__': 31 os.chdir(DOWNLOAD_PATH) 32 try: 33 file_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 34 file_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) 35 file_socket_port = int(input('请输入端口号:')) 36 file_socket.bind(('',file_socket_port)) 37 print('成功启动,等待连接。。。') 38 file_socket.listen(1) 39 f_socket, f_addr = file_socket.accept() 40 print(f'建立连接{f_addr}') 41 f_socket.send('请输入文件名'.encode('gbk')) 42 file_name = f_socket.recv(1024) 43 download(file_name.decode('gbk'),f_socket) 44 f_socket.close() 45 file_socket.close() 46 except ConnectionResetError: 47 print('发送端已断开连接') 48 except UnicodeDecodeError: 49 print('文件编码错误,请检查文件格式是否正确')