-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileServer.java
79 lines (50 loc) · 2.35 KB
/
FileServer.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
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
public class FileServer implements Runnable {
ServerSocket serverSocket;
FileServer() {
try {
serverSocket = new ServerSocket(Test.PORTNO); // same port number but over TCP instead of UDP
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
byte[] buffer = new byte[255]; // buffer size can be increased
while(true) {
try {
Socket connectionSocket = serverSocket.accept();
if(Test.DEBUG) System.out.println("TCP connection made with host " + connectionSocket.getInetAddress() );
InputStream connectionInputStream = connectionSocket.getInputStream();
OutputStream connectionOutputStream = connectionSocket.getOutputStream();
connectionInputStream.read(buffer); // blocks until data is received
String message = new String(buffer); // create a String out of the buffer
String[] tmp = message.trim().split(" +", 2);
if(tmp[0].equals("get")) {
if(Test.DEBUG) System.out.println("checking that file " + tmp[1] + " exists in my shared folder...");
File toBeServed = new File(Test.SHAREDFOLDERPATH + tmp[1]);
if(toBeServed.exists()) { // check file actually exists in shared folder
if(Test.DEBUG) System.out.println("Serving file...");
connectionOutputStream.write((tmp[1] + "\n" + toBeServed.length()+"\n").getBytes());
// connectionOutputStream.write(Files.readAllBytes(toBeServed.toPath())); // second call to write = OK ???
byte[] sendingBuffer = new byte[(int) toBeServed.length()];
FileInputStream fis = new FileInputStream(toBeServed);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(sendingBuffer, 0, sendingBuffer.length);
OutputStream os = connectionSocket.getOutputStream();
os.write(sendingBuffer, 0, sendingBuffer.length);
os.flush();
}
}
connectionSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}