文件下载.py

从一台计算机上下载文件到自己的计算机上

#服务端
from socket import *
from multiprocessing import Process
import os
def main():
    # 服务端文件根目录
    ROOT = os.path.dirname(os.path.abspath(__file__))
    s = socket(AF_INET,SOCK_STREAM)
    #绑定ip和端口
    s.bind(('172.16.11.199',8181))
    #监听客户端的连接请求
    s.listen(10)
    #连接循环
    while True:
        print('请稍等...')
        print(ROOT)
        connect, address = s.accept()
        # # 查看服务器内文件
        list_files = str(os.listdir(ROOT))
        print(list_files)
        data1 = connect.recv(1024)

        if data1.decode('utf-8')=='下载':
            connect.send(str(list_files).encode('utf-8'))

        p = Process(target=talk,args=(connect,ROOT))
        p.start()
        p.join()

    s.close()

def talk(connect,ROOT):
    #通信循环
    while True:
        name = connect.recv(1024)
        print(name)
        file_name = name.decode('utf-8')
        full_name = os.path.join(ROOT, file_name)
        print(full_name)
        # 判断文件是否存在
        if os.path.exists(full_name):
            # 文件大小
            file_size = os.path.getsize(full_name)
            # 将文件发送给客户端
            file_info = '%s|%d' % (file_name, file_size)
            connect.send(file_info.encode('utf-8'))
            # 打开
            with open(full_name, 'rb') as f:
                # 假设已经发送的字节数
                has_sent = 0
                while has_sent != file_size:
                    # 读取
                    data = f.read(1024)
                    # 发送
                    connect.sendall(data)
                    # 递增
                    has_sent += len(data)
                    # 接收服务器响应信息
                    print(has_sent)
            # 接收服务上传成功消息
            data2 = connect.recv(1024)
            print(data2.decode('utf-8'))
        else:
            print('文件不存在')


if __name__ == '__main__':
    main()



from socket import *
import os

def main():

    c = socket(AF_INET,SOCK_STREAM)
    #连接到服务器
    c.connect(('172.16.11.199',8181))
    #服务端文件所在目录
    ROOT = os.path.dirname(os.path.abspath(__file__))

    # #输入要下载的文件名
    name = input('>>>输入下载两字即可得到服务器文件列表: ').strip()

    c.send(name.encode('utf-8'))
    # 接收文件名和文件大小
    data1 = c.recv(1024)
    s1 = str(data1.decode('utf-8'))
    print(s1)

    while True:
        file = input(">>请输入你要下载的文件名: ").strip()
        c.send(file.encode('utf-8'))
        data2 = c.recv(1024)
        str1 = data2.decode('utf-8')
        file_name, file_size = str1.split('|')
        full_name = os.path.join(ROOT, file_name)
        with open(full_name, 'ab') as f:
            has_rec = 0
            while has_rec != int(file_size):
                # 接收文件数据
                data2 = c.recv(1024)
                f.write(data2)
                has_rec += len(data2)
                # print(has_rec)
            else:
                c.send('下载成功'.encode('utf-8'))


    c.close()
if __name__ == '__main__':
    main()

 

posted @ 2019-05-23 12:05  岩小鱼  阅读(938)  评论(0编辑  收藏  举报