1. 程式人生 > 其它 >使用UDP協議進行本地檔案傳輸(python version)

使用UDP協議進行本地檔案傳輸(python version)

技術標籤:計算機網路計算機網路socketpython

使用UDP協議,實現本地Client端和Server端的檔案傳輸,檔案可以是大檔案,圖片,也可以是視訊檔案等

Server端:

# -*- coding=utf-8 -*-
import socket
import time
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....')

received_size = 0
while
True: if count == 0: data,client_addr = s.recvfrom(4096) print('connected from %s:%s'%client_addr) # Record the start time of the receiver running start = time.time() f = open(data, 'wb') data, client_addr = s.recvfrom(4096) if str(data) != "b'end'"
: received_size += len(data) f.write(data) # Record the current system time end = time.time() # Print the current time every 1s # while printing the cumulative amount of transmission if end-start>1: print(end) print('Accept '
, received_size, ' B') start = time.time() else: break s.sendto('ok'.encode('utf-8'),client_addr) count+=1 print('total received ',received_size, ' B') f.close() s.close()

Client端:

# -*- coding=utf-8 -*-
import socket
import os
import time

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

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
while True:
    if count == 0:
        data = bytes(fname2, encoding = "utf8")
        # The start time of the sending end is recorded,
        # which is used to calculate the total running time and 1s respectively
        total_start = time.time()
        current_start = time.time()
        s.sendto(data,client_addr)
    data = f.read(4096)
    if str(data) != "b''":
        s.sendto(data,client_addr)
    else:
        s.sendto('end'.encode('utf-8'),client_addr)
        break
    current_end = time.time()
    # Print the timestamp of the sending end for every 1s
    if current_end-current_start>1:
        print(current_end)
        current_start = time.time()
    data, server_addr = s.recvfrom(4096)
    count+=1

s.close
total_end = time.time()
print('total cost: '+str(round(total_end-total_start,6))+'s')