/*
*DownLoadThread线程负责接受服务器传过来的数据;
*CommandThread线程负责控制DownLoadThread线程,并提供和用户交互的功能;
*/
import java.net.*;
import java.io.*;
public class FtpClient {
public static void main(String args[]) throws IOException {
Socket s;
DataInputStream dis;
DataOutputStream dos;
try{
s = new Socket("125.220.6.225", 4000);
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
DownLoadThread dlt=new DownLoadThread(dis);
dlt.start();
Thread.sleep(1);
new CommandThread(dos,dlt).start();
Thread.sleep(1);
}catch (IOException e){
}catch(InterruptedException e){
System.out.println(e);
}
}
}
class DownLoadThread extends Thread
{
static final int PAUSE=0;
static final int RUN=1;
static final int STOP=2;
private int state=RUN;
DataInputStream dis;
PrintWriter pw;
public DownLoadThread(DataInputStream dis){
this.dis=dis;
}
public synchronized void setState(int s){
state=s;
if(s==RUN||s==STOP)
notify();
}
public synchronized boolean checkState(){
if(state==PAUSE){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
if(state==RUN)
return true;
return false;
}
public void run(){
String key=null;
String message=null;
String content=null;
try{
pw=new PrintWriter(new FileWriter("D:\\DownLoad.txt"));
}catch(IOException e){
e.printStackTrace();
}
while(checkState()){
try{
Thread.sleep(400);
message=dis.readUTF();
}catch(Exception e){
System.out.println("EEEEEEEE");
}
key=message.substring(0,6);
content=message.substring(6);
if(key.equals("[dire]")){
System.out.println(content);
continue;
}
if(key.equals("[file]")){
pw.println(content);
pw.flush();
System.out.print("=");
}
}
}
}
class CommandThread extends Thread
{
DownLoadThread dlt;
DataOutputStream dos;
BufferedReader br;
String order;
boolean stop=false;
public CommandThread (DataOutputStream dos,DownLoadThread dlt){
this.dos=dos;
this.dlt=dlt;
br=new BufferedReader(new InputStreamReader(System.in));
}
public void run(){
try{
while(!stop){
order=br.readLine();
if(order.equalsIgnoreCase("pause"))
dlt.setState(0);
if(order.equalsIgnoreCase("run"))
dlt.setState(1);
if(order.equalsIgnoreCase("stop")){
dlt.setState(2);
stop=true;
}
if(order.equalsIgnoreCase("dir")){
System.out.print("In put the paht of the File:(C:\\)");
order="dire"+br.readLine();
dos.writeUTF(order);
}
if(order.equalsIgnoreCase("down")){
System.out.print("Which file you want to download:(C:\\dl.txt)");
order="down"+br.readLine();
dos.writeUTF(order);
}
}
}catch(IOException e){
}
finally{
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
System.out.println("The Connection is Closed!");
}
}
}