python socket 断点传输文件

最近研究了一下python在计算机之间断点传输的方法,主要是应对系统中断的发生。主要原理很简单,发送端每次发送文件时,首先接收来自于接收端的一个标志信息,告诉发送端已经接收到的字节数,然后从下一个字节开始发送即可。代码如下:

发送端:

import socket
import struct
import sys
import os
import time
 
 
if __name__ == '__main__':
 
    file_name = sys.argv[1]
 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((socket.gethostname(), 12345))
 
    # 定义文件头信息;
    file_head = struct.pack('128sl', os.path.basename(file_name).encode(),
                        os.stat(file_name).st_size)
 
    sock.send(file_head)
    
    received_size = int(sock.recv(2014).decode())
 
    read_file = open(file_name, "rb")
    read_file.seek(received_size)
    while True:
        # time.sleep(1)
        file_data = read_file.read(10240)
 
        if not file_data:
            break
 
        sock.send(file_data)
 
    read_file.close()
    sock.close()

添加了两行代码,注意read_file.seek(index)函数可以使下一次读取从index开始。

接收端代码:

import socket
import threading
import os
import struct
 
 
def sending_file(connection):
    try:
        file_info_size = struct.calcsize('128sl')
 
        buf = connection.recv(file_info_size)
 
        if buf:
            file_name, file_size = struct.unpack('128sl', buf)
            file_name = file_name.decode().strip('\00')
 
            file_new_dir = os.path.join('receive')
            # print(file_name, file_new_dir)
            if not os.path.exists(file_new_dir):
                os.makedirs(file_new_dir)
 
            file_new_name = os.path.join(file_new_dir, file_name)
			
            received_size = 0
            if os.path.exists(file_new_name):
                received_size = os.path.getsize(file_new_name)

            connection.send(str(received_size).encode())
 
            w_file = open(file_new_name, 'ab')
 
            print("start receiving file:", file_name)
 
            while not received_size == file_size:
 
                r_data = connection.recv(10240)
                received_size += len(r_data)
                w_file.write(r_data)
 
            w_file.close()
 
            print("接收完成!\n")
 
        connection.close()
 
    except Exception as e:
        print(e)
 
 
if __name__ == '__main__':
    host = socket.gethostname()
 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, 12345))
    sock.listen(5)
 
    print("服务已启动---------------")
 
    while True:
        connection, address = sock.accept()
        print("接收地址:", address)
        thread = threading.Thread(target=sending_file, args=(connection,))
        thread.start()

在接收数据之前,先查找本地已接收到的数据大小并反馈给发送端,然后才开始接收文件,从而实现断点续传。

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值