-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSrv3pm.java
More file actions
79 lines (63 loc) · 1.99 KB
/
FileSrv3pm.java
File metadata and controls
79 lines (63 loc) · 1.99 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
69
70
71
72
73
74
75
76
77
78
79
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
public class FileSrv3pm {
public static void main(String[] args) throws IOException {
System.out.println("I'm a web server that's a *file sever*...");
final String crlf = "\r\n";
int port = 11114;
ServerSocket ssock = new ServerSocket(port);
System.out.println("listening on port " + port + "...");
while (true) {
Socket sock = ssock.accept();
System.out.println("received a new client connection!");
OutputStream out = sock.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String req = "";
String line;
while ((line = in.readLine()) != null && !(line.equals("")) )
req += (line+crlf);
/*
if (line == null)
System.out.println("line == null");
else
System.out.println("line == " + line);
*/
if (req.length()==0) {
System.out.println("!!!!!!!empty request (?)");
continue;
}
System.out.println("at " + new Date() + ", req received:\n" + req);
System.out.println("req.length() = " + req.length());
String firstLine = req.split(crlf)[0];
String res = firstLine.split(" ")[1];
System.out.println("res req'ed: " + res);
Path pathfile = Paths.get("." + res);
boolean exists = Files.exists(pathfile);
String body;
String status;
byte[] content;
if (!exists) {
body = "<html><body>this file does not exist: " + pathfile + "</body></html>";
content = body.getBytes();
status = "404 File Not Found";
} else {
body = "the file exists; here's where its content should go";
status = "200 OK";
content = Files.readAllBytes(pathfile);
}
String head = "HTTP/1.1 " + status + crlf + "Connection: close" + crlf +
"Content-Length: " +
//body.length() +
content.length + crlf + crlf;
// String resp = head + body;
out.write(head.getBytes());
out.write(content);
out.flush();
out.close();
in.close();
sock.close();
}
}
}