ftp封装java
import java.io.*;
import java.net.*;public class ftpServer extends Thread{ public static void main(String args[]){
String initDir;
initDir = "D:/Ftp";
ServerSocket server;
Socket socket;
String s;
String user;
String password;
user = "root";
password = "123456";
try{
System.out.println("MYFTP服务器启动....");
System.out.println("正在等待连接....");
//监听21号端口
server = new ServerSocket(21);
socket = server.accept();
System.out.println("连接成功");
System.out.println("**********************************");
System.out.println("");
InputStream in =socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream din = new DataInputStream(in);
DataOutputStream dout=new DataOutputStream(out);
System.out.println("请等待验证客户信息....");
while(true){
s = din.readUTF();
if(s.trim().equals("LOGIN "+user)){
s = "请输入密码:";
dout.writeUTF(s);
s = din.readUTF();
if(s.trim().equals(password)){
s = "连接成功。";
dout.writeUTF(s);
break;
}
else{s ="密码错误,请重新输入用户名:";<br> dout.writeUTF(s);<br> <br> }
}
else{
s = "您输入的命令不正确或此用户不存在,请重新输入:";
dout.writeUTF(s);
}
}
System.out.println("验证客户信息完毕...."); while(true){
System.out.println("");
System.out.println("");
s = din.readUTF();
if(s.trim().equals("DIR")){
String output = "";
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
for(int i=0;i<dirStructure.length;i++){
output +=dirStructure[i]+"\n";
}
s=output;
dout.writeUTF(s);
}
else if(s.startsWith("GET")){
s = s.substring(3);
s = s.trim();
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
String e= s;
int i=0;
s ="不存在";
while(true){
if(e.equals(dirStructure[i])){
s="存在";
dout.writeUTF(s);
RandomAccessFile outFile = new RandomAccessFile(initDir+"/"+e,"r");
byte byteBuffer[]= new byte[1024];
int amount;
while((amount = outFile.read(byteBuffer)) != -1){
dout.write(byteBuffer, 0, amount);break;
}break;
}
else if(i<dirStructure.length-1){
i++;
}
else{
dout.writeUTF(s);
break;
}
}
}
else if(s.startsWith("PUT")){
s = s.substring(3);
s = s.trim();
RandomAccessFile inFile = new RandomAccessFile(initDir+"/"+s,"rw");
byte byteBuffer[] = new byte[1024];
int amount;
while((amount =din.read(byteBuffer) )!= -1){
inFile.write(byteBuffer, 0, amount);break;
}
}
else if(s.trim().equals("BYE"))break;
else{
s = "您输入的命令不正确或此用户不存在,请重新输入:";
dout.writeUTF(s);
}
}
din.close();
dout.close();
in.close();
out.close();
socket.close();
}
catch(Exception e){
System.out.println("MYFTP关闭!"+e);
}
}}
B. 如何用java连接到ftp上
现在已经封装好了的方法,不需要任何其他知识即可连接的。只需要知道ftp登录用户名、密码、端口、存储路径即可。
package zn.ccfccb.util;
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class CCFCCBFTP {
/**
* 上传文件
*
* @param fileName
* @param plainFilePath 明文文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上传文件开始");
Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// Log.info("连接远程上传服务器"+"192.168.54.106:"+2021);
// ftpClient.connect("192.168.54.106", 2021);
// ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz");
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("检查文件路径是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
/**
*下载并解压文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下载并解密文件开始");
Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;
ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下载文件开始。");
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下载文件结束:"+localFilePath);
}
}
Log.info("检查文件是否存:"+fileName+" "+bl);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。");
return bl;
}
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
C. JAVA 如何实现FTP远程路径
package nc.ui.doc.doc_007;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import nc.itf.doc.DocDelegator;
import nc.vo.doc.doc_007.DirVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;
public class FtpTool {
private FTPClient ftp;
private String romateDir = "";
private String userName = "";
private String password = "";
private String host = "";
private String port = "21";
public FtpTool(String url) throws IOException {
//String url="ftp://user:password@ip:port/ftptest/psd";
int len = url.indexOf("//");
String strTemp = url.substring(len + 2);
len = strTemp.indexOf(":");
userName = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("@");
password = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
host = "";
len = strTemp.indexOf(":");
if (len < 0)//没有设置端口
{
port = "21";
len = strTemp.indexOf("/");
if (len > -1) {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
strTemp = "";
}
} else {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("/");
if (len > -1) {
port = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
port = "21";
strTemp = "";
}
}
romateDir = strTemp;
ftp = new FTPClient();
ftp.connect(host, FormatStringToInt(port));
}
public FtpTool(String host, int port) throws IOException {
ftp = new FTPClient();
ftp.connect(host, port);
}
public String login(String username, String password) throws IOException {
this.ftp.login(username, password);
return this.ftp.getReplyString();
}
public String login() throws IOException {
this.ftp.login(userName, password);
System.out.println("ftp用户: " + userName);
System.out.println("ftp密码: " + password);
if (!romateDir.equals(""))
System.out.println("cd " + romateDir);
ftp.changeWorkingDirectory(romateDir);
return this.ftp.getReplyString();
}
public boolean upload(String pathname, String filename) throws IOException, BusinessException {
int reply;
int j;
String m_sfilename = null;
filename = CheckNullString(filename);
if (filename.equals(""))
return false;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("FTP server refused connection.");
System.exit(1);
}
FileInputStream is = null;
try {
File file_in;
if (pathname.endsWith(File.separator)) {
file_in = new File(pathname + filename);
} else {
file_in = new File(pathname + File.separator + filename);
}
if (file_in.length() == 0) {
System.out.println("上传文件为空!");
return false;
}
//产生随机数最大到99
j = (int)(Math.random()*100);
m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名
is = new FileInputStream(file_in);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.storeFile(m_sfilename, is);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
System.out.println("上传文件成功!");
return true;
}
public boolean delete(String filename) throws IOException {
FileInputStream is = null;
boolean retValue = false;
try {
retValue = ftp.deleteFile(filename);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
return retValue;
}
public void close() {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static int FormatStringToInt(String p_String) {
int intRe = 0;
if (p_String != null) {
if (!p_String.trim().equals("")) {
try {
intRe = Integer.parseInt(p_String);
} catch (Exception ex) {
}
}
}
return intRe;
}
public static String CheckNullString(String p_String) {
if (p_String == null)
return "";
else
return p_String;
}
public boolean downfile(String pathname, String filename) {
String outputFileName = null;
boolean retValue = false;
try {
FTPFile files[] = ftp.listFiles();
int reply = ftp.getReplyCode();
////////////////////////////////////////////////
if (!FTPReply.isPositiveCompletion(reply)) {
try {
throw new Exception("Unable to get list of files to dowload.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/////////////////////////////////////////////////////
if (files.length == 0) {
System.out.println("No files are available for download.");
}else {
for (int i=0; i <files.length; i++) {
System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());
outputFileName = pathname + filename + ".pdf";
//return outputFileName;
File f = new File(outputFileName);
//////////////////////////////////////////////////////
retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));
if (!retValue) {
try {
throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/////////////////////////////////////////////////////////////
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retValue;
}
}
D. 用Java实现FTP服务器解决方案
FTP 命令 FTP 的主要操作都是基于各种命令基础之上的 常用的命令有 · 设置传输模式 它包括ASCⅡ(文本) 和BINARY 二进制模式;· 目录操作 改变或显示远程计算机的当前目录(cd dir/ls 命令);· 连接操作 open命令用于建立同远程计算机的连接 close命令用于关闭连接;· 发送操作 put命令用于传送文件到远程计算机 mput 命令用于传送多滚隐个文件到远程计算机;· 获取操作 get命令用于接收一个文件 mget命令用于接收多个文件 编程思路 根据FTP 的工作原理 在主函数中建立一个服务器套接字端口 等待客户端请求 一旦客户端请求被接受 服务器程序就建立一个服务器分线程 处理客户端的命令 如果客户端需要和服务器端进行文件的传输 则建立一个新的套接字连接来完成文件的操作 编程技巧说明 主函数设计在主函数中 完成服务器端口的侦听和服务线程的创建 我们利用一个静态字符串变量initDir 来保存服务器线程运行时所在的工作目录 服务器的初始工作目录是由程序运行时用户输入的 缺省为C盘的根目录 具体的代码如下 public class ftpServer extends Thread{private Socket socketClient;private int counter;private static String initDir;public static void main(String[] args){if(args length != ) {initDir = args[ ];}else{ initDir = c: ;}int i = ;try{System out println( ftp server started! );//监听 号端口ServerSocket s = new ServerSocket( );for(;;){//接受客户端请求Socket ining = s accept();//创建服务御尺线程new ftpServer(ining i) start();i++;}}catch(Exception e){}} 线程类的设计线程类的主要设计都是在run()方法中实现 用run()方法得到客户端的套接字信息 根据套接字得到输入流和输出流 向客户端发送欢迎信息 FTP 命令的处理( ) 访问控制命令· user name(user) 和 password (pass) 命令处理代码如下 if(str startsWith( USER )){user = str substring( );user = user trim();out println( Password );}if(str startsWith( PASS ))out println( User +user+ logged in );User 命令和 Password 命令分别用来提交客户端用户输入的用户名和口令 · CWD (CHANGE WORKING DIRECTORY) 命令处理代码如下 if(str startsWith( CWD )){String str = str substring( );dir = dir+ / +str trim();out println( CWD mand succesful );}该命令改变工作目录到用户指定的目录 · CDUP (CHANGE TO PARENT DIRECTORY) 命令处理代码如下 if(str startsWith( CDUP )){int n = dir lastIndexOf( / );dir = dir substring( n);out println( CWD mand succesful );}该命令改变当前目录为上一层目录大拆厅 · QUIT命令处理代码如下 if(str startsWith( QUIT )) {out println( GOOD BYE );done = true;}该命令退出及关闭与服务器的连接 输出GOOD BYE ( ) 传输参数命令· Port命令处理代码如下 if(str startsWith( PORT )) {out println( PORT mand successful );int i = str length() ;int j = str lastIndexOf( );int k = str lastIndexOf( j );String str str ;str = ;str = ;for(int l=k+ ;lstr = str + str charAt(l);}for(int l=j+ ;l<=i;l++){str = str + str charAt(l);}tempPort = Integer parseInt(str ) * * +Integer parseInt(str );}使用该命令时 客户端必须发送客户端用于接收数据的 位IP 地址和 位 的TCP 端口号 这些信息以 位为一组 使用十进制传输 中间用逗号隔开 · TYPE命令处理代码如下 if(str startsWith( TYPE )){out println( type set );}TYPE 命令用来完成类型设置 ( ) FTP 服务命令· RETR (RETEIEVE) 和 STORE (STORE)命令处理的代码if(str startsWith( RETR )){out println( Binary data connection );str = str substring( );str = str trim();RandomAccessFile outFile = newRandomAccessFile(dir+ / +str r );Socket tempSocket = new Socket(host tempPort);OutputStream outSocket = tempSocket getOutputStream();byte byteBuffer[]= new byte[ ];int amount;try{while((amount = outFile read(byteBuffer)) != ){outSocket write(byteBuffer amount);}outSocket close();out println( transfer plete );outFile close();tempSocket close();}catch(IOException e){}}if(str startsWith( STOR )){out println( Binary data connection );str = str substring( );str = str trim();RandomAccessFile inFile = newRandomAccessFile(dir+ / +str rw );Socket tempSocket = new Socket(host tempPort);InputStream inSocket = tempSocket getInputStream();byte byteBuffer[] = new byte[ ];int amount;try{while((amount =inSocket read(byteBuffer) )!= ){inFile write(byteBuffer amount);}inSocket close();out println( transfer plete );inFile close();tempSocket close();}catch(IOException e){}}文件传输命令包括从服务器中获得文件RETR和向服务器中发送文件STOR 这两个命令的处理非常类似 处理RETR命令时 首先得到用户要获得的文件的名称 根据名称创建一个文件输入流 然后和客户端建立临时套接字连接 并得到一个输出流 随后 将文件输入流中的数据读出并借助于套接字输出流发送到客户端 传输完毕以后 关闭流和临时套接字 STOR 命令的处理也是同样的过程 只是方向正好相反 · DELE (DELETE)命令处理代码如下 if(str startsWith( DELE )){str = str substring( );str = str trim();File file = new File(dir str);boolean del = file delete();out println( delete mand successful );}DELE 命令用于删除服务器上的指定文件 · LIST命令处理代码如下 if(str startsWith( LIST )) {try{out println( ASCII data );Socket tempSocket = new Socket(host tempPort);PrintWriter out = new PrintWriter(tempSocket getOutputStream() true);File file = new File(dir);String[] dirStructure = new String[ ];dirStructure= file list();String strType= ;for(int i= ;iif( dirStructure[i] indexOf( ) == ) { strType = d ;}else{strType = ;}out println(strType+dirStructure[i]);}tempSocket close();out println( transfer plete );}catch(IOException e){}LIST 命令用于向客户端返回服务器中工作目录下的目录结构 包括文件和目录的列表 处理这个命令时 先创建一个临时的套接字向客户端发送目录信息 这个套接字的目的端口号缺省为 然后为当前工作目录创建File 对象 利用该对象的list()方法得到一个包含该目录下所有文件和子目录名称的字符串数组 然后根据名称中是否含有文件名中特有的 来区别目录和文件 最后 将得到的名称数组通过临时套接字发送到客户端 lishixin/Article/program/Java/JSP/201311/19211
E. 用java实现sftp的客户端,channel.connect()的时候,抛出异常,收到信息过长,然后就没连上。怎么回事
首先,不太明确你要问什么?
J2EE是java企业级应用,它里面关于安全方面的东西很多!
权限管理?信息安全?授权服务?访问控制?数据机密性?
要是你想全部都了解!
在这里提问是不行的!太庞杂了!
如果 你要问的是 java ftp传输过程中的一些安全注意事项!
这里建议 你使用 apache的开源项目。他们把基于java的ftp操作都封装好了!
安全相关都有保证。
我下面可以给你复制一段 ftp下载远程终端的java代码!你可以参考一下!
需要下载 org.apache.commons.net包
可以到 网站下载!
/**
* Description: 从FTP服务器下载文件
* @param ip FTP服务器的ip地址
* @param port FTP服务器端口,默认为:21
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath,String fileName,String localPath,String localfile) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//处理中文转码操作
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){
String localfilename = localfile;//按规则设置文件名这里你要下载文件,可以自己定义下载之后的文件名
File localFile = new File(localPath+File.separator+localfilename);
OutputStream is = new FileOutputStream(localFile);
//此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);
is.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
F. java做ftp服务器需要什么jar包
apache的包:commons-net.jar
主要使用到的类:
org.apache.commons.net.ftp.FTPClient;
org.apache.commons.net.ftp.FTPFile;
org.apache.commons.net.ftp.FTPReply;
JDK中也有自带的ftp包:
sun.net.ftp.下有FTP操作类
但sun已经不建议使用了, 建议楼主使用apache的包
G. java ftp 有哪些工具类
java ftp 最常用的是apache commons-net
commons-net项目中封装了各种网络协议的客户端,支持的协议包括:
FTP
NNTP
SMTP
POP3
Telnet
TFTP
Finger
Whois
rexec/rcmd/rlogin
Time (rdate) and Daytime
Echo
Discard
NTP/SNTP
其他的还有FTP4J ,jftp
H. 如何用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.");