python每日作业4/21

作业:
编写cs架构的软件,实现客户端可以下载服务端的文件,如图片、视频、文本等

服务端:

import socketserver
import subprocess
import struct
import os
import json

class MyRequestHandle(socketserver.BaseRequestHandler):
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    put_dir="file_put"

    def handle(self):
        # 如果tcp协议,self.request=>conn
        print(self.client_address)
        print("接到来自:{}的连接".format(self.client_address[0]))
        # 循环通信
        while True:
            data = self.request.recv(4)
            data_len = struct.unpack('i', data)[0]
            head_json = self.request.recv(data_len).decode("utf-8")
            head_dic = json.loads(head_json)
            # print(head_dic)
            cmd = head_dic['cmd']
            if hasattr(self, cmd):
                func = getattr(self, cmd)
                func(head_dic)

    def ls(self,head_dic):
        data={
            "file":{},
            "dir":[],
        }
        file_list=os.listdir(self.BASE_DIR)
        if not file_list:
            pass
        for name in file_list:
            if os.path.isfile(name):
                size=os.path.getsize(name)
                data["file"][name]=size
            elif os.path.isdir(name):
                data["dir"].append(name)

        head_json = json.dumps(data)
        head_json_bytes = bytes(head_json, encoding='utf-8')

        self.request.send(struct.pack('i', len(head_json_bytes)))
        self.request.send(head_json_bytes)


    def get(self,head_dic):
        filename=head_dic["filename"]
        filesize=0
        if not os.path.isfile(filename):
            data='file:%s is not exists' %filename
            self.request.send(struct.pack('i', filesize))
        filesize = os.path.getsize(filename)
        self.request.send(struct.pack('i', filesize))
        send_size = 0
        with open(filename, 'rb') as f:
            for line in f:
                self.request.send(line)
                send_size += len(line)
                print(send_size)
            else:
                print('successful')

    def put(self):
        pass

    def cd(self):
        pass





#  服务端应该做两件事
# 第一件事:循环地从半连接池中取出链接请求与其建立双向链接,拿到链接对象
s=socketserver.ThreadingTCPServer(('127.0.0.1',9000),MyRequestHandle)
s.serve_forever()
server

客户端:

import socket
import struct
import json
import os



class MYTCPClient:
    address_family = socket.AF_INET
    socket_type = socket.SOCK_STREAM
    allow_reuse_address = False
    max_packet_size = 8192
    request_queue_size = 5
    coding = 'utf-8'
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    download_dir = "file_get"

    def __init__(self, server_address, connect=True):
        self.server_address=server_address
        self.socket = socket.socket(self.address_family,
                                    self.socket_type)
        if connect:
            try:
                self.client_connect()
            except:
                self.client_close()
                raise

    def client_connect(self):
        self.socket.connect(self.server_address)

    def client_close(self):
        self.socket.close()

    def run(self):
        while True:
            inp=input(">>: ").strip()
            if not inp:continue
            l=inp.split()
            cmd=l[0]
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func(l)

    def ls(self,args):
        cmd = args[0]
        head_dic = {'cmd': cmd, 'filename': None}
        head_json = json.dumps(head_dic)
        head_json_bytes = bytes(head_json, encoding="utf-8")

        head_struct = struct.pack('i', len(head_json_bytes))
        self.socket.send(head_struct)
        self.socket.send(head_json_bytes)
        data = self.socket.recv(4)
        data_len = struct.unpack('i', data)[0]
        head_json = self.socket.recv(data_len).decode("utf-8")
        head_dic = json.loads(head_json)
        print("file:")
        for name,size in head_dic["file"].items():
            print("文件名:{}   文件大小【{}】Byte".format(name,size))
        print("dir:")
        for name in head_dic["dir"]:
            print("目录名:{}".format(name))

    def get(self,args):
        cmd = args[0]
        filename = args[1]
        head_dic = {'cmd': cmd, 'filename': filename}
        head_json = json.dumps(head_dic)
        head_json_bytes = bytes(head_json, encoding=self.coding)

        head_struct = struct.pack('i', len(head_json_bytes))
        self.socket.send(head_struct)
        self.socket.send(head_json_bytes)
        data=self.socket.recv(4)
        data_size=struct.unpack('i', data)[0]
        if not data_size:
            print("文件不存在")
            return
        recv_size = 0
        download_file_dir_path=os.path.join(self.BASE_DIR,self.download_dir)
        if not os.path.exists(download_file_dir_path):
            os.mkdir(download_file_dir_path)
        download_file_path=os.path.join(self.BASE_DIR,self.download_dir,filename)
        print('----->', download_file_path)
        with open(download_file_path, 'wb') as f:
            while recv_size < data_size:
                recv_data = self.socket.recv(self.max_packet_size)
                f.write(recv_data)
                recv_size += len(recv_data)
                print('recvsize:%s filesize:%s' % (recv_size, data_size))
            print("success")


    def put(self,args):
        cmd=args[0]
        filename=args[1]
        if not os.path.isfile(filename):
            print('file:%s is not exists' %filename)
            return
        else:
            filesize=os.path.getsize(filename)

        head_dic={'cmd':cmd,'filename':os.path.basename(filename),'filesize':filesize}
        head_json=json.dumps(head_dic)
        head_json_bytes=bytes(head_json,encoding=self.coding)

        head_struct=struct.pack('i',len(head_json_bytes))
        self.socket.send(head_struct)
        self.socket.send(head_json_bytes)
        send_size=0
        with open(filename,'rb') as f:
            for line in f:
                self.socket.send(line)
                send_size+=len(line)
                print(send_size)
            else:
                print('upload successful')

client=MYTCPClient(('127.0.0.1',9000))
client.run()
client

 

 

选做:
1、实现上传功能
2、服务端支持并发
3、阿里云服务器应用

 

posted @ 2020-04-21 22:18  耗油炒白菜  阅读(214)  评论(0编辑  收藏  举报