zoukankan      html  css  js  c++  java
  • socket ftp上传

    #client

    import socket
    import os,json



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

    def help(self):
    msg ='''
    is
    pwd
    cd ..
    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):
    file_size = os.stat(filename).st_size
    msg_dict = {
    "action":"put",
    "filename":filename,
    "size":file_size,
    "overridden":True
    }
    self.client.send(json.dumps(msg_dict).encode("utf-8"))
    #防止粘包,等待服务器确认
    server_response = self.client.recv(1024)
    f = open(filename,"rb")
    for line in f:
    self.client.send(line)
    else:
    print("file upload succuss..")
    f.close()

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

    ftp = FTPClient()
    ftp.connect("localhost",9999)
    ftp.interactive()


    #server
    import  socketserver
    import json,os
    class MyTCPHandler(socketserver.BaseRequestHandler):

    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")
    recevied_size =0
    while recevied_size<filesize:
    data =self.request.recv(1024)
    f.write(data)
    recevied_size += len(data)
    else:
    print("file [%s] has uploaded ..."%filename)
    def handle(self):
    while True:
    try:
    self.data = self.request.recv(1024).strip()
    print("{}worte".format(self.client_address[0]))
    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)

    except ConnectionRefusedError as e:
    print('error',e)
    break




    if __name__ == '__main__':
    HOST,PORT = "localhost",9999
    server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
    server.serve_forever()
  • 相关阅读:
    设计模式(十六):职责链模式
    设计模式(十五):状态模式
    设计模式(十四):命令模式
    设计模式(十三):模板模式
    设计模式(十二):观察者模式
    远程连接数据库常出现的错误解析
    [解决] Error Code: 1044. Access denied for user 'root'@'%' to database
    linux常用命令
    linux上svn项目管理,同步服务器,用户管理
    linux 磁盘分区
  • 原文地址:https://www.cnblogs.com/anhao-world/p/13587425.html
Copyright © 2011-2022 走看看