您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)python怎么實(shí)現(xiàn)UDP協(xié)議下的文件傳輸,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
UDP協(xié)議下文件傳輸:
服務(wù)端
import socket count = 0 s = 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+=1 print('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 socket import os import time def Get_FilePath_FileName_FileExt(filename): filepath, tempfilename = os.path.split(filename) shotname, extension = os.path.splitext(tempfilename) return filepath, shotname, extension s = 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 = 0 flag = 1 while 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+=1 print('recircled'+str(count)) s.close end = 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()
此次試驗(yàn)為100000Byte大小的文件,運(yùn)行后查看服務(wù)器端信息:
客戶端上查看傳輸時(shí)延:
關(guān)于“python怎么實(shí)現(xiàn)UDP協(xié)議下的文件傳輸”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。