-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileServer.java
More file actions
68 lines (59 loc) · 1.56 KB
/
FileServer.java
File metadata and controls
68 lines (59 loc) · 1.56 KB
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
import java.net.*;
import java.io.*;
import jatyc.lib.Typestate;
import jatyc.lib.Nullable;
@Typestate("FileServer")
public class FileServer {
private @Nullable Socket socket;
protected @Nullable OutputStream out;
protected @Nullable BufferedReader in;
protected @Nullable String lastFilename;
protected final int EOF = 0;
public boolean start(Socket s) {
try {
socket = s;
out = socket.getOutputStream();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hasRequest() throws Exception {
String command = in.readLine();
if (command != null && command.equals("REQUEST")) {
String filename = in.readLine();
if (filename != null) {
lastFilename = filename;
return true;
}
}
return false;
}
public void handleRequest() throws Exception {
try {
FileReader f = new FileReader(lastFilename);
int lastChar = f.read();
while(lastChar != -1) {
out.write(lastChar);
lastChar = f.read();
}
f.close();
} catch (FileNotFoundException e) {
// File not found
}
out.write(EOF);
}
public void close() throws Exception {
socket.close();
out.close();
in.close();
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(1234);
while (true) {
new FileServerThread(serverSocket.accept()).start();
}
}
}