FTP-Server

 

 

1.目录:

 

2. ftp_client.py

import socket,os,json
client=socket.socket()
client.connect(('localhost',9999))
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):
        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 successfully..')
                    f.close()

            else:
                print(filename,"is not exist")
    def cmd_get(self):
        pass

ftp=FtpClient()
ftp.connect('localhost',9999)
ftp.interactive()

 

3. Day8->ftp_server -> core ->main.py

 

import socketserver
import os,json

class MyTCPHandler(socketserver.BaseRequestHandler): #自己写的请求处理类,每个客户端的请求过来,都会实例它。MyTCPHandler
    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,'wb')
        self.request.send(b'200 ok')
        received_size=0
        while received_size<filesize:
            data=self.request.recv(1024)
            f.write(data)
            received_size=received_size+len(data)
        else:
            print('file uploaded successfully')

    def handle(self): #重写handle()
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                print("{} wrote:".format(self.client_address[0])) #打印客户端的IP地址
                print(self.data)
                cmd_dic=json.loads(self.data.decode())
                action=cmd_dic['action']
                if hasattr(self,action):
                    func=getattr(self,action)
                    func(cmd_dic)


                self.request.sendall(self.data.upper()) #变成大写,传回给客户端。
            except ConnectionResetError as e:
                print('Error is: ',e) #客户端断开时抛出的异常
                break

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

 

4.运行:实现从客户端到服务器端上传一个视频文件

 

 

客户端运行:

 

>>:put 02_python.avi
file upload successfully..
>>:

 服务器端运行结果:

127.0.0.1 wrote:
b'{"overridden": true, "filename": "02_python.avi", "action": "put", "size": 68601364}'
file uploaded successfully

 

posted on 2017-08-10 10:09  momo8238  阅读(216)  评论(0编辑  收藏  举报