Java完成FTP辦事器功效實例代碼。本站提示廣大學習愛好者:(Java完成FTP辦事器功效實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成FTP辦事器功效實例代碼正文
FTP(File Transfer Protocol 文件傳輸協定)是Internet 上用來傳送文件的協定。在Internet上經由過程FTP 辦事器可以停止文件的上傳(Upload)或下載(Download)。FTP是及時聯機辦事,在應用它之前必需是具有該辦事的一個用戶(用戶名和口令),任務時客戶端必需先登錄到作為辦事器一方的盤算機上,用戶登錄後可以停止文件搜刮和文件傳送等有關操作,如轉變以後任務目次、列文件目次、設置傳輸參數及傳送文件等。應用FTP可以傳送一切類型的文件,如文本文件、二進制可履行文件、圖像文件、聲響文件和數據緊縮文件等。
FTP 敕令
FTP 的重要操作都是基於各類敕令基本之上的。經常使用的敕令有:
設置傳輸形式,它包含ASCⅡ(文本) 和BINARY 二進制形式;
目次操作,轉變或顯示長途盤算機確當前目次(cd、dir/ls 敕令);
銜接操作,open敕令用於樹立同長途盤算機的銜接;close敕令用於封閉銜接;
發送操作,put敕令用於傳送文件到長途盤算機;mput 敕令用於傳送多個文件到長途盤算機;
獲得操作,get敕令用於吸收一個文件;mget敕令用於吸收多個文件。
import java.net.Socket; import org.apache.log4j.Logger; /** * 腳色——辦事器A * @author Leon * */ public class ServerA{ public static void main(String[] args){ final String F_DIR = "c:/test";//根途徑 final int PORT = 22;//監聽端標語 Logger.getRootLogger(); Logger logger = Logger.getLogger("com"); try{ ServerSocket s = new ServerSocket(PORT); logger.info("Connecting to server A..."); logger.info("Connected Successful! Local Port:"+s.getLocalPort()+". Default Directory:'"+F_DIR+"'."); while( true ){ //接收客戶端要求 Socket client = s.accept(); //創立辦事線程 new ClientThread(client, F_DIR).start(); } } catch(Exception e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } } import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.net.ConnectException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.Random; import org.apache.log4j.Logger; /** * 客戶端子線程類 * @author Leon * */ public class ClientThread extends Thread { private Socket socketClient;//客戶端socket private Logger logger;//日記對象 private String dir;//相對途徑 private String pdir = "/";//絕對途徑 private final static Random generator = new Random();//隨機數 public ClientThread(Socket client, String F_DIR){ this.socketClient = client; this.dir = F_DIR; } @Override public void run() { Logger.getRootLogger(); logger = Logger.getLogger("com"); InputStream is = null; OutputStream os = null; try { is = socketClient.getInputStream(); os = socketClient.getOutputStream(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); PrintWriter pw = new PrintWriter(os); String clientIp = socketClient.getInetAddress().toString().substring(1);//記載客戶端IP String username = "not logged in";//用戶名 String password = "";//口令 String command = "";//敕令 boolean loginStuts = false;//登錄狀況 final String LOGIN_WARNING = "530 Please log in with USER and PASS first."; String str = "";//敕令內容字符串 int port_high = 0; int port_low = 0; String retr_ip = "";//吸收文件的IP地址 Socket tempsocket = null; //打印迎接信息 pw.println("220-FTP Server A version 1.0 written by Leon Guo"); pw.flush(); logger.info("("+username+") ("+clientIp+")> Connected, sending welcome message..."); logger.info("("+username+") ("+clientIp+")> 220-FTP Server A version 1.0 written by Leon Guo"); boolean b = true; while ( b ){ try { //獲得用戶輸出的敕令 command = br.readLine(); if(null == command) break; } catch (IOException e) { pw.println("331 Failed to get command"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 331 Failed to get command"); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } b = false; } /* * 拜訪掌握敕令 */ // USER敕令 if(command.toUpperCase().startsWith("USER")){ logger.info("(not logged in) ("+clientIp+")> "+command); username = command.substring(4).trim(); if("".equals(username)){ pw.println("501 Syntax error"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 501 Syntax error"); username = "not logged in"; } else{ pw.println("331 Password required for " + username); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 331 Password required for " + username); } loginStuts = false; } //end USER // PASS敕令 else if(command.toUpperCase().startsWith("PASS")){ logger.info("(not logged in) ("+clientIp+")> "+command); password = command.substring(4).trim(); if(username.equals("root") && password.equals("root")){ pw.println("230 Logged on"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 230 Logged on"); // logger.info("客戶端 "+clientIp+" 經由過程 "+username+"用戶登錄"); loginStuts = true; } else{ pw.println("530 Login or password incorrect!"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 530 Login or password incorrect!"); username = "not logged in"; } } //end PASS // PWD敕令 else if(command.toUpperCase().startsWith("PWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ // logger.info("用戶"+clientIp+":"+username+"履行PWD敕令"); pw.println("257 /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 257 /""+pdir+"/" is current directory"); } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end PWD // CWD敕令 else if(command.toUpperCase().startsWith("CWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ str = command.substring(3).trim(); if("".equals(str)){ pw.println("250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); } else{ //斷定目次能否存在 String tmpDir = dir + "/" + str; File file = new File(tmpDir); if(file.exists()){//目次存在 dir = dir + "/" + str; if("/".equals(pdir)){ pdir = pdir + str; } else{ pdir = pdir + "/" + str; } // logger.info("用戶"+clientIp+":"+username+"履行CWD敕令"); pw.println("250 CWD successful. /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 CWD successful. /""+pdir+"/" is current directory"); } else{//目次不存在 pw.println("550 CWD failed. /""+pdir+"/": directory not found."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 550 CWD failed. /""+pdir+"/": directory not found."); } } } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end CWD // QUIT敕令 else if(command.toUpperCase().startsWith("QUIT")){ logger.info("("+username+") ("+clientIp+")> "+command); b = false; pw.println("221 Goodbye"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 221 Goodbye"); try { Thread.currentThread(); Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } //end QUIT /* * 傳輸參數敕令 */ //PORT敕令,自動形式傳輸數據 else if(command.toUpperCase().startsWith("PORT")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ try { str = command.substring(4).trim(); port_low = Integer.parseInt(str.substring(str.lastIndexOf(",")+1)); port_high = Integer.parseInt(str.substring(0, str.lastIndexOf(",")) .substring(str.substring(0, str.lastIndexOf(",")).lastIndexOf(",")+1)); String str1 = str.substring(0, str.substring(0, str.lastIndexOf(",")).lastIndexOf(",")); retr_ip = str1.replace(",", "."); try { //實例化自動形式下的socket tempsocket = new Socket(retr_ip,port_high * 256 + port_low); // logger.info("用戶"+clientIp+":"+username+"履行PORT敕令"); pw.println("200 port command successful"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 200 port command successful"); } catch (ConnectException ce) { pw.println("425 Can't open data connection."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 425 Can't open data connection."); logger.error(ce.getMessage()); for(StackTraceElement ste : ce.getStackTrace()){ logger.error(ste.toString()); } } catch (UnknownHostException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } catch (NumberFormatException e) { pw.println("503 Bad sequence of commands."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 503 Bad sequence of commands."); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end PORT //PASV敕令,主動形式傳輸數據 else if(command.toUpperCase().startsWith("PASV")) { logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ ServerSocket ss = null; while( true ){ //獲得辦事器余暇端口 port_high = 1 + generator.nextInt(20); port_low = 100 + generator.nextInt(1000); try { //辦事器綁定端口 ss = new ServerSocket(port_high * 256 + port_low); break; } catch (IOException e) { continue; } } // logger.info("用戶"+clientIp+":"+username+"履行PASV敕令"); InetAddress i = null; try { i = InetAddress.getLocalHost(); } catch (UnknownHostException e1) { e1.printStackTrace(); } pw.println("227 Entering Passive Mode ("+i.getHostAddress().replace(".", ",")+","+port_high+","+port_low+")"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 227 Entering Passive Mode ("+i.getHostAddress().replace(".", ",")+","+port_high+","+port_low+")"); try { //主動形式下的socket tempsocket = ss.accept(); ss.close(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end PASV //RETR敕令 else if(command.toUpperCase().startsWith("RETR")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ str = command.substring(4).trim(); if("".equals(str)){ pw.println("501 Syntax error"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 501 Syntax error"); } else { try { pw.println("150 Opening data channel for file transfer."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 150 Opening data channel for file transfer."); RandomAccessFile outfile = null; OutputStream outsocket = null; try { //創立從中讀取和向個中寫入(可選)的隨機拜訪文件流,該文件具有指命名稱 outfile = new RandomAccessFile(dir+"/"+str,"r"); outsocket = tempsocket.getOutputStream(); } catch (FileNotFoundException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } byte bytebuffer[]= new byte[1024]; int length; try{ while((length = outfile.read(bytebuffer)) != -1){ outsocket.write(bytebuffer, 0, length); } outsocket.close(); outfile.close(); tempsocket.close(); } catch(IOException e){ logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } // logger.info("用戶"+clientIp+":"+username+"履行RETR敕令"); pw.println("226 Transfer OK"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 226 Transfer OK"); } catch (Exception e){ pw.println("503 Bad sequence of commands."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 503 Bad sequence of commands."); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } }//end RETR //STOR敕令 else if(command.toUpperCase().startsWith("STOR")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ str = command.substring(4).trim(); if("".equals(str)){ pw.println("501 Syntax error"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 501 Syntax error"); } else { try { pw.println("150 Opening data channel for file transfer."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 150 Opening data channel for file transfer."); RandomAccessFile infile = null; InputStream insocket = null; try { infile = new RandomAccessFile(dir+"/"+str,"rw"); insocket = tempsocket.getInputStream(); } catch (FileNotFoundException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } byte bytebuffer[] = new byte[1024]; int length; try{ while((length =insocket.read(bytebuffer) )!= -1){ infile.write(bytebuffer, 0, length); } insocket.close(); infile.close(); tempsocket.close(); } catch(IOException e){ logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } // logger.info("用戶"+clientIp+":"+username+"履行STOR敕令"); pw.println("226 Transfer OK"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 226 Transfer OK"); } catch (Exception e){ pw.println("503 Bad sequence of commands."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 503 Bad sequence of commands."); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } } else { pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end STOR //NLST敕令 else if(command.toUpperCase().startsWith("NLST")) { logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ try { pw.println("150 Opening data channel for directory list."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 150 Opening data channel for directory list."); PrintWriter pwr = null; try { pwr= new PrintWriter(tempsocket.getOutputStream(),true); } catch (IOException e1) { e1.printStackTrace(); } File file = new File(dir); String[] dirstructure = new String[10]; dirstructure= file.list(); for(int i=0;i<dirstructure.length;i++){ pwr.println(dirstructure[i]); } try { tempsocket.close(); pwr.close(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } // logger.info("用戶"+clientIp+":"+username+"履行NLST敕令"); pw.println("226 Transfer OK"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 226 Transfer OK"); } catch (Exception e){ pw.println("503 Bad sequence of commands."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 503 Bad sequence of commands."); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } }else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end NLST //LIST敕令 else if(command.toUpperCase().startsWith("LIST")) { logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ try{ pw.println("150 Opening data channel for directory list."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 150 Opening data channel for directory list."); PrintWriter pwr = null; try { pwr= new PrintWriter(tempsocket.getOutputStream(),true); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } FtpUtil.getDetailList(pwr, dir); try { tempsocket.close(); pwr.close(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } // logger.info("用戶"+clientIp+":"+username+"履行LIST敕令"); pw.println("226 Transfer OK"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 226 Transfer OK"); } catch (Exception e){ pw.println("503 Bad sequence of commands."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 503 Bad sequence of commands."); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } else { pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end LIST // 輸出不法敕令 else{ logger.info("("+username+") ("+clientIp+")> "+command); pw.println("500 Syntax error, command unrecognized."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 500 Syntax error, command unrecognized."); } } //end while try { logger.info("("+username+") ("+clientIp+")> disconnected."); // logger.info("用戶"+clientIp+":"+username+"加入"); br.close(); socketClient.close(); pw.close(); if(null != tempsocket){ tempsocket.close(); } } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } } } import java.io.File; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; /** * FTP對象類 * @author Leon * */ public class FtpUtil { public static void getDetailList(PrintWriter pw, String path){ File dir = new File(path); if (!dir.isDirectory()) { pw.println("500 No such file or directory./r/n"); } File[] files = dir.listFiles(); String modifyDate; for (int i = 0; i < files.length; i++) { modifyDate = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss") .format(new Date(files[i].lastModified())); if (files[i].isDirectory()) { pw.println("drwxr-xr-x ftp ftp 0 " + modifyDate + " " + files[i].getName()); } else { pw.println("-rw-r-r--1 ftp ftp " + files[i].length() + " " + modifyDate + " " + files[i].getName()); } pw.flush(); } pw.println("total:" + files.length); } } ### set log levels ### log4j.logger.com =debug,stdout,D,E ### 輸入到掌握台 ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n ## 輸入DEBUG級別以上的日記 log4j.appender.D=org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File=c:/logs/logs.log log4j.appender.D.Append =true ## 輸入DEBUG級別以上的日記 log4j.appender.D.Threshold=DEBUG log4j.appender.D.layout=org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 保留異常信息到零丁文件 ### log4j.appender.E=org.apache.log4j.DailyRollingFileAppender ## 異常日記文件名 log4j.appender.E.File=c:/logs/errors.log log4j.appender.E.Append=true ## 只輸入ERROR級別以上的日記!!! log4j.appender.E.Threshold=ERROR log4j.appender.E.layout=org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
以上內容是小編給年夜家引見的Java完成FTP辦事器功效實例代碼的相干常識,願望年夜家愛好。