您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關python如何實現TCP文件傳輸的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
實現代碼:
服務端:
import socket import time s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind(('127.0.0.1',9999)) s.listen(5) print('Waiting for connection...') while True: sock,addr = s.accept() print('Accept new connection from %s:%s...' % addr) if count == 0: data1 = sock.recv(1024) print(str(data1)) file_total_size = int(data1.decode()) received_size = 0 sock.send('received'.encode()) data = sock.recv(1024) filepath = str(data.decode()) f = open(filepath, 'wb') while received_size < file_total_size: data = sock.recv(1024) f.write(data) received_size += len(data) print('已接收 ',received_size,' Byte') data = sock.recv(1024) if data == b'end': break f.close() s.close()
客戶端:
import socket import os import time filename = input('please enter the filename you want to send:\n') filesize = str(os.path.getsize(filename)) fname1, fname2 = os.path.split(filename) client_addr = ('127.0.0.1',9999) f = open(filename,'rb') count = 0 flag = 1 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立連接: s.connect(('127.0.0.1', 9999)) while True: if count == 0: s.send(filesize.encode()) start = time.time() s.recv(1024) s.send(fname2.encode()) for line in f: s.send(line) print('sending...') s.send(b'end') break s.close end = time.time() print('cost' + str(round(end - start, 2)) + 's')
運行截圖:
服務器端:
客戶端:
感謝各位的閱讀!關于“python如何實現TCP文件傳輸”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。