使用UDP协议进行本地文件传输(python version)

使用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')

欢迎访问我的博客:https://colinasda.github.io/
随手记录一些计算机相关的知识点以及分享一些资源

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值