python实现文件断点续传

#! /usr/bin/env python
# -*- coding:utf-8 -*-

import socket
import os

sock = socket.socket()
sock.bind(("127.0.0.1", 8080))
sock.listen(5)

had_recv = 0

while True:
    conn, client_address = sock.accept()

    first_recv = str(conn.recv(1024),encoding="utf-8")
    src_path, file_size, dst_path = first_recv.split(" ",3)
    total_size = int(file_size)
    if os.path.exists(dst_path):
        had_recv = os.stat(dst_path).st_size
        conn.sendall(bytes("Y-" + str(had_recv), encoding="utf-8"))
        # 为了避免粘包问题
        reponse = conn.recv(1024)
        print(str(reponse, encoding="utf-8"))
        f = open(dst_path, "ab")
    else:
        conn.sendall(bytes("N", encoding="utf-8"))
        # 为了避免粘包问题
        reponse = conn.recv(1024)
        print(str(reponse, encoding="utf-8"))
        f = open(dst_path, "wb")
    #文件已接收完,关闭连接,结束
    while True:
        if total_size == had_recv:
            conn.close()
            break
        data = conn.recv(1024)
        f.write(data)
        had_recv += len(data)
        print(had_recv,total_size)


client

#! /usr/bin/env python
# -*- coding:utf-8 -*-

import socket
import os

sock = socket.socket()
sock.bind(("127.0.0.1", 8080))
sock.listen(5)

had_recv = 0

while True:
    conn, client_address = sock.accept()

    first_recv = str(conn.recv(1024),encoding="utf-8")
    src_path, file_size, dst_path = first_recv.split(" ",3)
    total_size = int(file_size)
    if os.path.exists(dst_path):
        had_recv = os.stat(dst_path).st_size
        conn.sendall(bytes("Y-" + str(had_recv), encoding="utf-8"))
        # 为了避免粘包问题
        reponse = conn.recv(1024)
        print(str(reponse, encoding="utf-8"))
        f = open(dst_path, "ab")
    else:
        conn.sendall(bytes("N", encoding="utf-8"))
        # 为了避免粘包问题
        reponse = conn.recv(1024)
        print(str(reponse, encoding="utf-8"))
        f = open(dst_path, "wb")
    #文件已接收完,关闭连接,结束
    while True:
        if total_size == had_recv:
            conn.close()
            break
        data = conn.recv(1024)
        f.write(data)
        had_recv += len(data)
        print(had_recv,total_size)






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值