Android端與Android端利用WIFI進行FTP通訊

一.客戶端通訊工具類:java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * 用於Android和FTP服務器進行交互的工具類
 */
public class FTPUtils {
    private FTPClient ftpClient = null;
    private static FTPUtils ftpUtilsInstance = null;
    private String ftpUrl;
    private int ftpPort;
    private String userName;
    private String userPassword;
    private final int connectTimeout = 5000;

    private FTPUtils() {
        ftpClient = new FTPClient();
    }

    /*
     * 獲得類對象實例(由於只能有一個這樣的類對象,因此用單例模式)
     */
    public static FTPUtils getInstance() {
        if (ftpUtilsInstance == null) {
            ftpUtilsInstance = new FTPUtils();
        }
        return ftpUtilsInstance;
    }

    /**
     * 設置FTP服務器
     * 
     * @param FTPUrl
     *            FTP服務器ip地址
     * @param FTPPort
     *            FTP服務器端口號
     * @param UserName
     *            登錄FTP服務器的帳號
     * @param UserPassword
     *            登錄FTP服務器的密碼
     * @return
     */
    public boolean initFTPSetting(String FTPUrl, int FTPPort, String UserName,
            String UserPassword) {
        ftpUrl = FTPUrl;
        ftpPort = FTPPort;
        userName = UserName;
        userPassword = UserPassword;

        int reply;

        try {
            //設定鏈接超時時間
            ftpClient.setConnectTimeout(connectTimeout);
            
            // 要鏈接的FTP服務器Url,Port
            ftpClient.connect(FTPUrl, FTPPort);

            // 登錄FTP服務器
            ftpClient.login(UserName, UserPassword);

            // 看返回的值是否是230,若是是,表示登錄成功
            reply = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                // 斷開
                ftpClient.disconnect();
                return false;
            }

            return true;

        } catch (SocketException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 斷開FTP服務器
     */
    public boolean disconnectFTP(){
        try {
            ftpClient.disconnect();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 上傳文件
     * 
     * @param FilePath
     *            要上傳文件所在SDCard的路徑
     * @param FileName
     *            要上傳的文件的文件名(如:Sim惟一標識碼)
     * @return true爲成功,false爲失敗
     */
    public boolean uploadFile(String FilePath, String FileName) {

        if (!ftpClient.isConnected()) {
            if (!initFTPSetting(ftpUrl, ftpPort, userName, userPassword)) {
                return false;
            }
        }

        try {

            // 設置存儲路徑
//            ftpClient.makeDirectory("/FtpFileTest");
//            ftpClient.changeWorkingDirectory("/FtpFileTest");

            // 設置上傳文件須要的一些基本信息
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            // 文件上傳吧~
            FileInputStream fileInputStream = new FileInputStream(FilePath);
            ftpClient.storeFile(FileName, fileInputStream);
            
            // 關閉文件流
            fileInputStream.close();

            // 退出登錄FTP,關閉ftpCLient的鏈接
            ftpClient.logout();
            ftpClient.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    /**
     * 下載文件
     * 
     * @param FilePath
     *            要存放的文件的路徑
     * @param FileName
     *            遠程FTP服務器上的那個文件的名字
     * @return true爲成功,false爲失敗
     */
    public boolean downLoadFile(String FilePath, String FileName) {

        if (!ftpClient.isConnected()) {
            if (!initFTPSetting(ftpUrl, ftpPort, userName, userPassword)) {
                return false;
            }
        }

        try {
            // 轉到指定下載目錄
            ftpClient.changeWorkingDirectory("/data");

            // 列出該目錄下全部文件
            FTPFile[] files = ftpClient.listFiles();

            // 遍歷全部文件,找到指定的文件
            for (FTPFile file : files) {
                if (file.getName().equals(FileName)) {
                    // 根據絕對路徑初始化文件
                    File localFile = new File(FilePath);

                    // 輸出流
                    OutputStream outputStream = new FileOutputStream(localFile);

                    // 下載文件
                    ftpClient.retrieveFile(file.getName(), outputStream);

                    // 清除緩存
                    outputStream.flush();
                    
                    // 關閉流
                    outputStream.close();
                }
            }

            // 退出登錄FTP,關閉ftpCLient的鏈接
            ftpClient.logout();
            ftpClient.disconnect();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return true;
    }
}


二.利用Android設備做爲FTP服務器,如下是FTPServer類android

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import android.os.Environment;

public class FtpServerlet extends DefaultFtplet{
    
    private FtpServer mFtpServer;
    
    private final int mPort = 2121;
    
    private final String mDirectory = Environment.getExternalStorageDirectory().getPath() + "/FtpFileTest";
    
    private final String mUser = "way";
    
    private final String mPassword = "way";
    
    private static FtpServerlet mInstance;
    
    public static FtpServerlet getInstance(){
        if(mInstance == null){
            mInstance = new FtpServerlet();
        }
        return mInstance;
    }
    
    /**
     * FTP啓動
     * @throws FtpException
     */
    public void start() throws FtpException {
        
        if (null != mFtpServer && false == mFtpServer.isStopped()) {
            return;
        }

        File file = new File(mDirectory);
        if (!file.exists()) {
            file.mkdirs();
        }

        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory listenerFactory = new ListenerFactory();

        // 設定端末番號
        listenerFactory.setPort(mPort);

        // 經過PropertiesUserManagerFactory建立UserManager而後向配置文件添加用戶
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
        UserManager userManager = userManagerFactory.createUserManager();

        List<Authority> auths = new ArrayList<Authority>();
        Authority auth = new WritePermission();
        auths.add(auth);
       
        //添加用戶
        BaseUser user = new BaseUser();
        user.setName(mUser);
        user.setPassword(mPassword);
        user.setHomeDirectory(mDirectory);
        user.setAuthorities(auths);
        userManager.save(user);

        // 設定Ftplet
        Map<String, Ftplet> ftpletMap = new HashMap<String, Ftplet>();
        ftpletMap.put("Ftplet", this);

        serverFactory.setUserManager(userManager);
        serverFactory.addListener("default", listenerFactory.createListener());
        serverFactory.setFtplets(ftpletMap);

        // 建立並啓動FTPServer
        mFtpServer = serverFactory.createServer();
        mFtpServer.start();
    }
    
    /**
     * FTP中止
     */
    public void stop() {
        
        // FtpServer不存在和FtpServer正在運行中
        if (null != mFtpServer && false == mFtpServer.isStopped()) {
            mFtpServer.stop();
        }
    }
    
    @Override
    public FtpletResult onAppendStart(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        System.out.println("onAppendStart");
        return super.onAppendStart(session, request);
    }

    @Override
    public FtpletResult onAppendEnd(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        System.out.println("onAppendEnd");
        return super.onAppendEnd(session, request);
    }
    
    @Override
    public FtpletResult onLogin(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        System.out.println("onLogin");
        return super.onLogin(session, request);
    }
    
    @Override
    public FtpletResult onConnect(FtpSession session) throws FtpException,
            IOException {
        System.out.println("onConnect");
        return super.onConnect(session);
    }

    @Override
    public FtpletResult onDisconnect(FtpSession session) throws FtpException,
            IOException {
        System.out.println("onDisconnect");
        return super.onDisconnect(session);
    }
    
    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        System.out.println("onUploadStart");
        return super.onUploadStart(session, request);
    }

    @Override
    public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        String FtpUploadPath    = mDirectory            + "/" + request.getArgument();
        //接收到文件後當即刪除
        File uploadFile = new File(FtpUploadPath);
        uploadFile.delete();
        return super.onUploadEnd(session, request);
    }
}

 

三.客戶端和服務器的AndroidManifest中添加相關權限
<!--容許應用打開網絡套接口 -->
<uses-permission android:name="android.permission.INTERNET"/>apache

<!--容許應用訪問關於Wi-Fi網絡的信息 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>緩存

<!-- 容許應用寫用戶的外部存儲器 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>服務器

<!-- 容許應用進入Wi-Fi的組播方式 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />網絡

<!-- 容許應用改變Wi-Fi的鏈接狀態 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>session

<!-- 容許應用改變網絡的鏈接狀態 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>ide

<!-- 容許應用訪問網絡上的信息 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>工具

 

四.所需jar包this

commons-net-3.0.1.jar  

ftpserver-core-1.0.6.jar  

找了半天不知道怎麼上傳附件,只能麻煩你們本身去下載了。

相關文章
相關標籤/搜索