public class Downloader extends Thread {
public final int DEFAULT_CLIENT_PORT = 8765;
private FileInformation serverFile;
private String path;
private Socket socket = null;
private DataOutputStream out = null;
private DataInputStream in = null;
private File localFile = null;
private FileOutputStream fileOutStream = null;
byte[] fileData =new byte[4096];
int byteNumber=0;
public Downloader (FileInformation serverFile, String path){
this.serverFile=serverFile;
this.path=path;
}
public void run(){
try{
socket=new Socket(serverFile.getFileLocation(),DEFAULT_CLIENT_PORT);
ObjectOutputStream obj = new ObjectOutputStream(socket.getOutputStream());
obj.writeObject(serverFile); //send request
obj.flush();
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
localFile = new File(path + serverFile.getFileName());
if (!localFile.exists()) {
fileOutStream = new FileOutputStream(localFile);
//download
while ((byteNumber = in.read(fileData)) != -1) {
fileOutStream.write(fileData, 0, byteNumber);
}
//--
fileOutStream.close();
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
if (localFile.exists()) localFile.delete();
}
}
}
-------------------------------------------------------------
public class DownloadListener extends Thread{
public final int DEFAULT_CLIENT_PORT=8765;
private Socket client;
private ServerSocket listener;
private DataInputStream in;
private DataOutputStream out;
private FileInputStream fileInStream;
public DownloadListener(){
super();
try{
listener= new ServerSocket(DEFAULT_CLIENT_PORT);
start();
} catch(IOException e){
e.printStackTrace();
}
}
public void close(){
try{
listener.close();
} catch(IOException e){
e.printStackTrace();
}
}
public void run(){
try{
do{
client=listener.accept();
ObjectInputStream obj= new ObjectInputStream(client.getInputStream());
FileInformation fileinfo =( FileInformation) obj.readObject();// get request
client.setSoTimeout(1000);
in=new DataInputStream(client.getInputStream());
out=new DataOutputStream(client.getOutputStream());
File localfile=new File(fileinfo.getFullPath());
fileInStream =new FileInputStream(localfile);
byte[] fileData=new byte[4096];
int byteNumber;
while ((byteNumber= fileInStream.read(fileData))!=-1)
{ out.write(fileData,0,byteNumber);}
fileInStream.close();
in.close();
out.close();
}while(!listener.isClosed());
}
catch (SocketException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}