-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileDownloader.java
103 lines (64 loc) · 2.88 KB
/
FileDownloader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDownloader implements SimpleMessageHandler, Runnable {
MuxDemuxSimple md;
public void run() {
while(true){
// take files to be downloaded from the download queue and download them from the appropriate peer, in the appropriate folder in the sharedfolder
try {
DownloadObject mydo = md.downloadQueue.take();
if(md.getbyID(mydo.getSenderID()).getPeerState().equals("synchronized")){
// create new socket corresponding to the sender's IP address
InetAddress peerInetAddress = InetAddress.getByName(md.getbyID(mydo.getSenderID()).getPeerIPAddress());
Socket socketToSender = new Socket(peerInetAddress, Test.PORTNO);
// send the appropriate request for mydo.fileName
socketToSender.getOutputStream().write(("get " + mydo.getFileName()+"\n").getBytes());
// then write buffer in the corresponding file
// BufferedReader br = new BufferedReader(new InputStreamReader(socketToSender.getInputStream()));
// socketToSender.getInputStream().read(buffer);
// String line="";
String filePath = Test.ROOTFOLDERERPATH + mydo.getSenderID() + "/" + mydo.getFileName();
// PrintWriter out = new PrintWriter(filePath);
// while (line!=null){
// line=br.readLine();
// out.write(line);
//
// }
InputStream in = socketToSender.getInputStream();
// Writing the file to disk
// Instantiating a new output stream object
OutputStream output = new FileOutputStream(filePath);
// byte[] buffer = new byte[1024];
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
bufferedReader.readLine();
String tmp;
if((tmp = bufferedReader.readLine()) != null) {
int fileSizeInBytes = Integer.parseInt(tmp);
byte[] buffer = new byte[fileSizeInBytes];
in.read(buffer);
output.write(buffer, 0, fileSizeInBytes);
}
// Closing the FileOutputStream handle
output.close();
socketToSender.close();
}
}
catch (Exception e) {
if(Test.DEBUG)
e.printStackTrace();
}
}
}
@Override
public void handleMessage(String m) {
// TODO Auto-generated method stub
}
@Override
public void setMuxDemux(MuxDemuxSimple muxDemuxSimple) {
md = muxDemuxSimple;
}
}