python实现TCP文件传输

时间:2021-05-22

前几天已经讲过了UDP协议下大文件传输的python实现代码,今天再实现TCP协议下大文件传输的python实现代码。
TCP和UDP的实现过程还是比较不一样的。

实现代码:

服务端:

import socketimport times = 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 socketimport osimport timefilename = 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 = 0flag = 1s = 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') breaks.closeend = time.time()print('cost' + str(round(end - start, 2)) + 's')

运行截图:

服务器端:

客户端:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章