这篇文章给大家分享的是有关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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。