python实现UDP协议下的文件传输

时间:2021-05-22

本文实例为大家分享了python实现UDP文件传输的具体代码,供大家参考,具体内容如下

UDP协议下文件传输:

服务端

import socketcount = 0s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)server_addr = ('127.0.0.1',9999)s.bind(server_addr)print('Bind UDP on 9999...')while True: if count == 0: data,client_addr = s.recvfrom(1024) print('connected from %s:%s'%client_addr) f = open(data, 'wb') data, client_addr = s.recvfrom(1024) if str(data) != "b'end'": f.write(data) print('recieved '+str(count)+' byte') else: break s.sendto('ok'.encode('utf-8'),client_addr) count+=1print('recercled'+str(count))f.close()s.close() # data, addr = s.recvfrom(1024) # print('Received from %s:%s' %addr) # s.sendto(b'Hello, %s!' %data, addr)

客户端

import socketimport osimport timedef Get_FilePath_FileName_FileExt(filename): filepath, tempfilename = os.path.split(filename) shotname, extension = os.path.splitext(tempfilename) return filepath, shotname, extensions = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)filename = input('please enter the filename you want to send:\n')filepath, shotname, extension = Get_FilePath_FileName_FileExt(filename)client_addr = ('127.0.0.1',9999)f = open(filename,'rb')count = 0flag = 1while True: if count == 0: data = bytes(shotname+extension, encoding = "utf8") start = time.time() s.sendto(data,client_addr) data = f.read(1024) if str(data) != "b''": s.sendto(data,client_addr) print(str(count)+'byte') else: s.sendto('end'.encode('utf-8'),client_addr) break data, server_addr = s.recvfrom(1024) count+=1print('recircled'+str(count))s.closeend = time.time()print('cost'+str(round(end-start,2))+'s')# for data in [b'Michael',b'Tracy',b'Sarah']:# s.sendto(data,('127.0.0.1',9999))# print(s.recv(1024).decode('utf-8'))# s.close()

此次试验为100000Byte大小的文件,运行后查看服务器端信息:

客户端上查看传输时延:

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

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

相关文章