⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpclient.java

📁 一个利用Java语言实现的ftp程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * Created on 2004-7-21
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package client;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * @author luofei
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class FtpClient {
	
	static final boolean debug = false;

    public static final int FTP_PORT = 21; 

    static int  FTP_SUCCESS = 1;
    static int  FTP_TRY_AGAIN = 2;
    static int  FTP_ERROR = 3;

    /** socket for data transfer */
    private Socket      dataSocket = null;
    private boolean     replyPending = false;
    private boolean     binaryMode = false;
    private boolean     passiveMode = false;
    /** user name for login */
    String              user = null;
    /** password for login */
    String              password = null;

    /** last command issued */
    String              command;

    /** The last reply code from the ftp daemon. */
    int                 lastReplyCode;

    /** Welcome message from the server, if any. */
    public String       welcomeMsg;

    /** Array of strings (usually 1 entry) for the last reply
        from the server. */
    protected Vector    serverResponse = new Vector(1);

    /** Socket for communicating with server. */
    protected Socket    serverSocket = null;

    /** Stream for printing to the server. */
    public PrintWriter  serverOutput;

    /** Buffered stream for reading replies from server. */
    public InputStream  serverInput;


    /** Return server connection status */
    public boolean serverIsOpen() {
        return serverSocket != null;
    }

	/**Set Passive mode Trasfers*/
	public void setPassive(boolean mode) {
		passiveMode = mode;
	}
	
    public int readServerResponse() throws IOException {
        StringBuffer    replyBuf = new StringBuffer(32);
        int             c;
        int             continuingCode = -1;
        int             code = -1;
        String          response;
        if (debug) System.out.println("readServerResponse start");
 
        try{
        	while (true) {
            	//if (debug) System.out.println("readServerResponse outer while loop: "+ serverInput.available());
           
            		while ((c = serverInput.read()) != -1) {
  
            			if (c == '\r') {
                    			if ((c = serverInput.read()) != '\n')
                        		replyBuf.append('\r');
                		}
                		replyBuf.append((char)c);               
                		if (c == '\n')
                    			break;                
            		}
 
            		if (debug) System.out.println("Now past inner while loop");

            		response = replyBuf.toString();
            		replyBuf.setLength(0);
            		if (debug) {
                		System.out.print(response);
            		}
            		try {
                		code = Integer.parseInt(response.substring(0, 3));
            		} catch (NumberFormatException e) {
                		code = -1;
            		} catch (StringIndexOutOfBoundsException e) {
                	/* this line doesn't contain a response code, so
                   		we just completely ignore it */
                		continue;
            		}
            		serverResponse.addElement(response);
            		if (continuingCode != -1) {
                	/* we've seen a XXX- sequence */
                		if (code != continuingCode ||
                    				(response.length() >= 4 && response.charAt(3) == '-')) {
                    			continue;
                		} else {
                    			/* seen the end of code sequence */
                    			continuingCode = -1;
                    			break;
                		}
            		} else if (response.length() >= 4 && response.charAt(3) == '-') {
                		continuingCode = code;
                		continue;
            		} else {
                		break;
            		}
        	}
        }
	 catch(Exception e){
	 	e.printStackTrace();
	 }
	
        if (debug) 
		System.out.println("readServerResponse done");

	 return lastReplyCode = code;
    }

    /** Sends command <i>cmd</i> to the server. */
    public void sendServer(String cmd) {
        if (debug) System.out.println("sendServer start");
        serverOutput.println(cmd);
        if (debug) System.out.println("sendServer done");

    }
   
    /** Returns all server response strings. */
    public String getResponseString() {
        String s = new String();
        for(int i = 0;i < serverResponse.size();i++) {
           s+=serverResponse.elementAt(i);
        }
        serverResponse = new Vector(1);
        return s;
    }

   public String getResponseStringNoReset() {
        String s = new String();
        for(int i = 0;i < serverResponse.size();i++) {
           s+=serverResponse.elementAt(i);
        }
        return s;
    }


    /** 
     * issue the QUIT command to the FTP server and close the connection. 
     */
    public void closeServer() throws IOException {
        if (serverIsOpen()) {
            issueCommand("QUIT");
        if (! serverIsOpen()) {
              return;
            }
            serverSocket.close();
            serverSocket = null;
            serverInput = null;
            serverOutput = null;
        }
    }

    protected int issueCommand(String cmd) throws IOException {
        command = cmd;

        int reply;
        if (debug) System.out.println(cmd);
        if (replyPending) {
            if (debug) System.out.println("replyPending");
            if (readReply() == FTP_ERROR)
                System.out.print("Error reading pending reply\n");
        }
        replyPending = false;
        do {
            sendServer(cmd);
            reply = readReply();
            //if (debug) System.out.println("in while loop of issueCommand method");
        } while (reply == FTP_TRY_AGAIN);
        return reply;
    }

    protected void issueCommandCheck(String cmd) throws IOException {
        if (debug) System.out.println("issueCommandCheck");
        if (issueCommand(cmd) != FTP_SUCCESS) {            
            throw new FtpProtocolException(cmd);
            }
    }

    protected int readReply() throws IOException {
        lastReplyCode = readServerResponse();

        switch (lastReplyCode / 100) {
        case 1:
            replyPending = true;
            /* falls into ... */

        case 2://This case is for future purposes. If not properly used, it might cause an infinite loop. 
               //Don't add any code here , unless you know what you are doing.
                
        case 3:
            return FTP_SUCCESS;

        case 5:
            if (lastReplyCode == 530) {
                if (user == null) {
                    throw new FtpLoginException("Not logged in");
                }
                return FTP_ERROR;
            }
            if (lastReplyCode == 550) {
                if (!command.startsWith("PASS"))
                     throw new FileNotFoundException(command);
                else
                     throw new FtpLoginException("Error: Wrong Password!");     
            }
        }

        /* this statement is not reached */
        return FTP_ERROR;
    }

     protected Socket openDataConnection(String cmd) throws IOException {
        ServerSocket portSocket = null;
        String       portCmd;
        InetAddress  myAddress = InetAddress.getLocalHost();
        byte         addr[] = myAddress.getAddress();
        int          shift;
        String       ipaddress;
        int          port = 0;
        IOException  e;
	 if (this.passiveMode) {

        	/* First let's attempt to initiate Passive transfers */
	
        	try {    // PASV code
        		getResponseString();
        		if (issueCommand("PASV") == FTP_ERROR) {
          			e = new FtpProtocolException("PASV");
          			throw e;
        		}
        		String reply = getResponseStringNoReset();
        		reply = reply.substring(reply.lastIndexOf("(")+1,reply.lastIndexOf(")"));
        		StringTokenizer st = new StringTokenizer(reply, ",");
        		String[] nums = new String[6];
        		int i = 0;
		
	 		while(st.hasMoreElements()) {
				try {
					 	nums[i] = st.nextToken();
					  	i++;
				} catch(Exception a){a.printStackTrace();}
			}
		
			ipaddress = nums[0]+"."+nums[1]+"."+nums[2]+"."+nums[3];

		 	try {
				int firstbits = Integer.parseInt(nums[4]) << 8;
			 	int lastbits = Integer.parseInt(nums[5]);
				port = firstbits + lastbits;
			} catch(Exception b) {b.printStackTrace();}

			if((ipaddress != null) && (port != 0)) {
				dataSocket = new Socket(ipaddress, port);
			} else{
				e = new FtpProtocolException("PASV");
				throw e;
			}

			if (issueCommand(cmd) == FTP_ERROR) {
				e = new FtpProtocolException(cmd);
				throw e;
			}

		} 
		catch (FtpProtocolException fpe) {  // PASV was not supported...resort to PORT

			portCmd = "PORT ";

			/* append host addr */
			for (int i = 0; i < addr.length; i++) {
				portCmd = portCmd + (addr[i] & 0xFF) + ",";
			}
       		try {
       			portSocket = new ServerSocket(20000);
        	 		/* append port number */
        			portCmd = portCmd + ((portSocket.getLocalPort() >>> 8) & 0xff) + ","
             								+ (portSocket.getLocalPort() & 0xff);
        			if (issueCommand(portCmd) == FTP_ERROR) {
          				e = new FtpProtocolException("PORT");
          				throw e;
       			}

      				if (issueCommand(cmd) == FTP_ERROR) {
       				e = new FtpProtocolException(cmd);
          				throw e;
       			}
       			dataSocket = portSocket.accept();
			}
       		finally {
       			if(portSocket != null)
          				portSocket.close();
      			}

			dataSocket = portSocket.accept();
			portSocket.close();

		}
	}//end if passive
	else {  //do a port transfer

       	portCmd = "PORT ";

      		/* append host addr */
      		for (int i = 0; i < addr.length; i++) {
       		portCmd = portCmd + (addr[i] & 0xFF) + ",";
      		}
      		try {
         		portSocket = new ServerSocket(20000);
         		/* append port number */
        		portCmd = portCmd + ((portSocket.getLocalPort() >>> 8) & 0xff) + ","
             									+ (portSocket.getLocalPort() & 0xff);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -