- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallCat01.java
More file actions
Latest commit
95 lines (84 loc) · 3.09 KB
/
Copy pathSmallCat01.java
File metadata and controls
95 lines (84 loc) · 3.09 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.text.DateFormat;
importjava.text.SimpleDateFormat;
importjava.util.Calendar;
importjava.util.Locale;
importjava.util.TimeZone;
publicclassSmallCat01 {
privatestaticfinalStringDOCUMENT_ROOT = "/opt/homebrew/var/www";
//InputStream에서 바이트열을 행단위로 읽어들이는 유틸리티
privatestaticStringreadLine(InputStreaminput) throwsIOException {
intch;
Stringret = "";
while ((ch = input.read()) != 1) {
// 개행문자가 아닌 동안 반복 (\r\n)
if (ch == '\r') {
continue;
} elseif (ch == '\n') {
break;
} else {
ret += (char) ch;
}
}
if (ch == -1) { // 다음 데이터가 없는 경우
returnnull;
} else {
returnret;
}
}
// 1행의 문자열을 바이트열로 OutputStream으로 쓰는
// 유틸리티
privatestaticvoidwriteLine(OutputStreamoutput, Stringstr) throwsIOException {
for (charch : str.toCharArray()) {
output.write((int) ch);
}
output.write((int) '\r');
output.write((int) '\n');
}
// 현재시각을 HTTP 표준 포맷에 맞게 날짜 문자열을 반환
privatestaticStringgetDateStringUtc() {
Calendarcal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
DateFormatdf = newSimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);
df.setTimeZone(cal.getTimeZone());
returndf.format(cal.getTime()) + " GMT";
}
publicstaticvoidmain(String[] args) {
try (ServerSocketserver = newServerSocket(8001)) {
Socketsocket = server.accept();
InputStreaminput = socket.getInputStream();
Stringline;
Stringpath = null;
while ((line = readLine(input)) != null) {
if (line == "") {
break;
}
if (line.startsWith("GET")) {
path = line.split(" ")[1]; // StatusLine 읽어서 요청 경로 추출
}
}
OutputStreamoutput = socket.getOutputStream();
// 리스폰스 헤더를 반환
writeLine(output, "HTTP/1.1 200 OK");
writeLine(output, "Date: " + getDateStringUtc());
writeLine(output, "Server: SmallCat/0.1");
writeLine(output, "Connection: close");
writeLine(output, "Content-type: text/html");
writeLine(output, "");
// 리스폰스 바디를 반환
try (FileInputStreamfis = newFileInputStream(DOCUMENT_ROOT + path)) {
intch;
while ((ch = fis.read()) != -1) {
output.write(ch);
}
}
socket.close();
} catch (Exceptione) {
e.printStackTrace();
}
}
}