ftp升级版

import socketserver
import json
import os

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
    def put(self,*args):
        cmd_dic=args[0]
        filename=cmd_dic["filename"]
        filesize=cmd_dic["size"]
        if os.path.isfile(filename):
            f=open(filename+".new","wb")


        else:
            f = open(filename + ".new", "wb")
        self.request.send(b"200 ok")
        received_size = 0
        while received_size < filesize:
            data=self.request.recv(1024)
            f.write(data)
            received_size+=len(data)
        else:
            print("file [%s] has uoloading...."%filename)

    def handle(self):
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                print("{} wrote:".format(self.client_address[0]))
                print(self.data)
                cmd_dic=json.loads(self.data.decode("utf-8"))
                action=cmd_dic["action"]
                if hasattr(self,action):
                    func=getattr(self,action)
                    func(cmd_dic)  #通过反射解耦

            except ConnectionResetError as e:
                print("erro",e)
                break

if __name__ == "__main__":
    HOST, PORT = "localhost",9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
    --------------------------------
    import socket, os, json


class FtpClient(object):
    def __init__(self):
        self.client = socket.socket()

    def help(self):
        msg = '''
        ls
        pwd
        cd ../..
        get filename
        put filename
        '''
        print(msg)

    def connect(self,ip,port):
        self.client.connect((ip,port))

    def interactive(self):
        # self.authentic
        while True:
            cmd = input(">>").strip()
            if len(cmd) == 0: continue
            cmd_str = cmd.split()[0]  # 反射解析命令
            if hasattr(self, "cmd_%s" % cmd_str):
                func = getattr(self, "cmd_%s" % cmd_str)
                func(cmd)
            else:
                self.help()

    def cmd_put(self, *args):
        cmd_split = args[0].split()
        if len(cmd_split) > 1:
            filename = cmd_split[1]
            if os.path.isfile(filename):
                filesize = os.stat(filename).st_size
                msg_dic = {
                    "action": "put",
                    "filename": filename,
                    "size": filesize,
                    "overridden": True
                }

                self.client.send(json.dumps(msg_dic).encode())
                # 防止粘包,等服务器确认
                server_response = self.client.recv(1024)
                f=open(filename,"rb")
                for line in f :
                    self.client.send(line)
                else:
                    print("file upload success...")
                    f.close()
            else:
                print(filename, "is not exit")

    def cmd_get(self):
        pass

ftp=FtpClient()
ftp.connect("localhost",9999)
ftp.interactive()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值