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)






你可能感兴趣的:(python)