1、 登陆
采用FTP进行文件传输,其实本质上还是采用Java.net.socket进行通信。以下代码只是类net.sf.jftp.net.FtpConnection其中一个login方法。当然在下面的代码,为了节省版面,以及将一些原理阐述清楚,笔者将一些没必要的代码去掉了,如日志等代码。完整的代码请参考J-ftp的源代码或是笔者所以的示例源代码,后面的代码示例也同理:
public int login(String username, String password)
{
this.username = username;
this.password = password;
int status = LOGIN_OK;
jcon = new JConnection(host, port);
if(jcon.isThere())
{
in = jcon.getReader();
if(getLine(POSITIVE) == null)//FTP220_SERVICE_READY) == null)
{
ok = false;
status = OFFLINE;
}
if(!getLine(loginAck).startsWith(POSITIVE))//FTP230_LOGGED_IN))
{
if(success(POSITIVE))//FTP230_LOGGED_IN))
{
}
else
{
ok = false;
status = WRONG_LOGIN_DATA;
}
}
}
else
{
if(msg)
{
Log.debug("FTP not available!");
ok = false;
status = GENERIC_FAILED;
}
}
if(ok)
{
connected = true;
system();
binary();
String[] advSettings = new String[6];
if(getOsType().indexOf("OS/2") >= 0)
{
//just get the first item (somehow it knows first is the
//FTP list command)
advSettings = LoadSet.loadSet(Settings.adv_settings);
//*** IF FILE NOT FOUND, CREATE IT AND SET IT TO LIST_DEFAULT
if(advSettings == null)
{
LIST = LIST_DEFAULT;
SaveSet s = new SaveSet(Settings.adv_settings, LIST);
}
else
{
LIST = advSettings[0];
if(LIST == null)
{
LIST = LIST_DEFAULT;
}
}
}
if(getOsType().indexOf("MVS") >= 0)
{
LIST = "LIST";
}
//***
fireDirectoryUpdate(this);
fireConnectionInitialized(this);
}
else
{
fireConnectionFailed(this, new Integer(status).toString());
}
return status;
}
此
登陆方法中,有一个JConnection类,此类负责建立socket套接字 ,同时,此类是一种单独的线程,这样的好处是为了配合界面的变化,
而将网络的套接字连接等工作做为单独的线程来处理,有利于界面的友好性。下面是net.sf.jftp.net.JConnection类的run方法,
当然,此线程的启动是在JConnection类的构造方法中启动的。
public void run()
{
try
{
s = new Socket(host, port);
localPort = s.getLocalPort();
//if(time > 0) s.setSoTimeout(time);
out = new PrintStream(new BufferedOutputStream(s.getOutputStream(),
Settings.bufferSize));
in = new BufferedReader(new InputStreamReader(s.getInputStream()),
Settings.bufferSize);
isOk = true;
// }
}
catch(Exception ex)
{
ex.printStackTrace();
Log.out("WARNING: connection closed due to exception (" + host +
":" + port + ")");
isOk = false;
try
{
if((s != null) && !s.isClosed())
{
s.close();
}
if(out != null)
{
out.close();
}
if(in != null)
{
in.close();
}
}
catch(Exception ex2)
{
ex2.printStackTrace();
Log.out("WARNING: got more errors trying to close socket and streams");
}
}
established = true;
}