Android搭建ftp服务器/客户端

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40391500/article/details/82116628

jar包链接https://download.csdn.net/download/weixin_40391500/10629775
ftp服务器

不设置读写权限是不能上传的文件的

private static String hostip = ""; // 本机IP
    public static final int PORT = 21;
    // sd卡目录
    @SuppressLint("SdCardPath")
//    public static final String dir = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static final String dir = "/mnt/sdcard/";
    public static final String dirname = dir + "face/";
    // ftp服务器配置文件路径
    private static final String filename = dirname + "users.properties";
    private static FtpServer mFtpServer = null;
    private String properties ="ftpserver.user.admin.userpassword=E10ADC3949BA59ABBE56E057F20F883E\r\n
        ftpserver.user.admin.homedirectory=/mnt/sdcard/ftp\r\n
        ftpserver.user.admin.enableflag=true\r\n
        ftpserver.user.admin.writepermission=true\r\n
        ftpserver.user.admin.maxloginnumber=4\r\n
        ftpserver.user.admin.maxloginperip=4\r\n
        ftpserver.user.admin.idletime=3000\r\n
        ftpserver.user.admin.uploadrate=4800\r\n
        ftpserver.user.admin.downloadrate=4800\r\n";

    public synchronized static FTPServerUtils getIntance(){
        if(utils == null){
            utils = new FTPServerUtils();
        }
        return utils;
    }
    /**
     * 创建服务器配置文件
     */
    public void creatDirsFiles(){
        try {
            File dir = new File(dirname);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fos = null;
            File sourceFile = new File(filename);
            if (sourceFile.exists()){
                sourceFile.delete();
            }
            fos = new FileOutputStream(sourceFile);
            fos.write(properties.getBytes());
            if (fos != null) {
                fos.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 开启FTP服务器
     *
     * @param hostip 本机ip
     */
    public void startFtpServer(final String hostip) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                if (!new File(filename).exists()){
//                    creatDirsFiles();
//                }
                creatDirsFiles();
                FtpServerFactory serverFactory = new FtpServerFactory();
                PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
                File files = new File(filename);
                //设置配置文件
                userManagerFactory.setFile(files);
                serverFactory.setUserManager(userManagerFactory.createUserManager());

                // 设置监听IP和端口号
                ListenerFactory factory = new ListenerFactory();
                factory.setPort(PORT);
                factory.setServerAddress(hostip);
                serverFactory.addListener("default", factory.createListener());
                BaseUser user = new BaseUser();

                //设置权限
                List<Authority> authorities = new ArrayList<>();
                authorities.add(new WritePermission());
                user.setAuthorities(authorities);
                //设置用户名密码
                user.setName("admin");
                user.setPassword("123456");
                user.setEnabled(true);
                user.setMaxIdleTime(3000);
                user.setHomeDirectory(dirname);
                try {
                    serverFactory.getUserManager().save(user);
                } catch (FtpException e) {
                    e.printStackTrace();
                }
                if(mFtpServer != null)
                {
                    mFtpServer.stop();
                }
                // start the server
                mFtpServer = serverFactory.createServer();
                try {
                    mFtpServer.start();
//                    FTPClientUtils.getIntance().ftpConnet();
                    LogUtils.printLog("开启了FTP服务器  ip = " + hostip);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
        /**
     * 关闭FTP服务器
     */
    public void stopFtpServer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mFtpServer != null) {
                    mFtpServer.stop();
                    mFtpServer = null;
                    LogUtils.printLog("关闭了FTP服务器 ip = " + hostip);
                }
            }
        }).start();
    }

    /**
     * 获取本机ip
     */
    public String getLocalIpAddress() {
        try {
            List<NetworkInterface> interfaces = Collections
                    .list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf
                        .getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = Isipv4(sAddr);
                        if (isIPv4) {
                            return sAddr;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public void onStartServer() {
        hostip = getLocalIpAddress();
        LogUtils.printLog("获取本机IP = " + hostip);
        startFtpServer(hostip);

    }
    public static boolean Isipv4(String ipv4) {
        if (ipv4 == null || ipv4.length() == 0) {
            return false;//字符串为空或者空串
        }
        //因为java doc里已经说明, split的参数是reg, 即正则表达式, 如果用"|"分割, 则需使用"\\|"
        String[] parts = ipv4.split("\\.");
        if (parts.length != 4) {//分割开的数组根本就不是4个数字
            return false;
        }
        for (int i = 0; i < parts.length; i++) {
            try {
                int n = Integer.parseInt(parts[i]);
                //数字不在正确范围内
                if (n < 0 || n > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {//转换数字不正确
                return false;
            }
        }
        return true;
    }

ftp客户端

public void ftpConnet(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client = new FTPClient();
                    String host = "192.168.1.114";
                    client.connect(host, 21);
                    client.login("admin", "123456");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void ftpClose(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (client !=null)
                        client.disconnect(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /***下载文件***/
    public void download(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (client != null){
                        String url = "/11.jpg";//服务器上的文件
                        PrintlnLog.printLog("-----------------url=" + url);
                        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftp");
                        if (!file.exists()){
                            file.mkdirs();
                        }
                                        File file1 = new File(file, "11.jpg");
                        client.download(url, file1, new FTPDataTransferListener() {
                            @Override
                            public void started() {
                                PrintlnLog.printLog("-----------------started");
                            }

                            @Override
                            public void transferred(int i) {
        //                    PrintlnLog.printLog("-----------------transferred");
                            }

                            @Override
                            public void completed() {
                                PrintlnLog.printLog("-----------------completed");
                            }

                            @Override
                            public void aborted() {
                                PrintlnLog.printLog("-----------------aborted");
                            }

                            @Override
                            public void failed() {
                                PrintlnLog.printLog("-----------------failed");
                            }
                        });
                    }else {
                        PrintlnLog.printLog("-----------------client=null");
//                ftpConnet();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /***上傳文件***/
    public void upload(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (client != null){
                        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/12.jpg");
                        if (!file.exists()){
                            file.mkdirs();
                        }
                        client.createDirectory("file");
                        client.changeDirectory("file");
                        client.upload(file, new FTPDataTransferListener() {
                            @Override
                            public void started() {
                                PrintlnLog.printLog("-----------------started");
                            }

                            @Override
                            public void transferred(int i) {
                                //                    PrintlnLog.printLog("-----------------transferred");
                            }

                            @Override
                            public void completed() {
                                PrintlnLog.printLog("-----------------completed");
                            }

                            @Override
                            public void aborted() {
                                PrintlnLog.printLog("-----------------aborted");
                            }

                            @Override
                            public void failed() {
                                PrintlnLog.printLog("-----------------failed");
                            }
                        });
                        client.changeDirectory("/");
                     }else {
                        PrintlnLog.printLog("-----------------client=null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

猜你喜欢

转载自blog.csdn.net/weixin_40391500/article/details/82116628
0条评论
添加一条新回复