-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadHTTPServer.java
205 lines (185 loc) · 7.13 KB
/
ThreadHTTPServer.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
* HTTP Server, Multi Threaded
* Usage: java ThreadHTTPServer [port# [http_root_path]]
*
**/
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
class HTTPThread implements Runnable {
private Socket clientSocket;
private String http_root_path;
private String check = null;
// constructor to instantiate the HTTPThread object
public HTTPThread(Socket connectionSocket, String http_root_path) {
this.clientSocket = connectionSocket;
this.http_root_path = http_root_path;
}
public void run() {
try {
// invoke processRequest() to process the client request and then generateResponse()
// to output the response message
this.processRequest(this.clientSocket);
} catch (Exception ex) {
Logger.getLogger(HTTPThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void processRequest(Socket connectionSocket) throws Exception {
BufferedReader inFromClient;
String requestLine = null;
try {
inFromClient = new BufferedReader
(new InputStreamReader(this.clientSocket.getInputStream()));
requestLine = inFromClient.readLine(); // ADD_CODE
} catch (IOException ex) {
Logger.getLogger(HTTPThread.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(requestLine);
/*try{
requestHeader = inFromClient.readLine();
check = requestHeader.substring(requestHeader.indexOf(":"));
}catch (Exception e){
continue;
}*/
// now back to the request line; tokenize the request
// same as in single-threaded (this code is inline in the starter code)
StringTokenizer tokenizedLine = new StringTokenizer(requestLine);
// process the request
if (tokenizedLine.nextToken().equals("GET")) {
String urlName = null;
// parse URL to retrieve file name
urlName = tokenizedLine.nextToken();
if (urlName.startsWith("/") == true )
urlName = urlName.substring(1);
try {
this.generateResponse(urlName, clientSocket);
} catch (Exception ex) {
Logger.getLogger(HTTPThread.class.getName()).log(Level.SEVERE, null, ex);
}
}else
System.out.println("Bad Request Message");
}
private static String getContentType(String fileloc){
//Find the content type of the file
if (fileloc.endsWith(".html")||fileloc.endsWith(".htm") ){
return "text/html";
}
else if (fileloc.endsWith(".css")){
return "text/css";
}
else if (fileloc.endsWith(".js")){
return "text/javascript";
}
else if (fileloc.endsWith(".jpg") ||
fileloc.endsWith(".jpeg")){
return "image/jpeg";
}
else{
return "text/plain";
}
}
private void generateResponse(String urlName, Socket connectionSocket) throws Exception {
// ADD_CODE: create an output stream
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
//Assume there is a slash at the end of root path
String fileLoc = http_root_path + urlName;// ADD_CODE: map urlName to rooted path
System.out.println ("Request Line: GET " + fileLoc);
File file = new File( fileLoc );
if (!file.isFile())
{
// generate 404 File Not Found response header
outToClient.writeBytes("HTTP/1.0 404 File Not Found\r\n");
// and output a copy to server's stdout
System.out.println ("HTTP/1.0 404 File Not Found\r\n");
} else {
// get the requested file content
int numOfBytes = (int) file.length();
FileInputStream inFile = new FileInputStream (fileLoc);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
String content = getContentType(fileLoc);
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
if (check != null && f.parse(check).getTime() > file.lastModified()){
System.out.println("HTTP/1.0 304 Not Modified");
}else{
// ADD_CODE: generate HTTP response line; output to stdout
System.out.println("HTTP/1.0 200 OK");
// ADD_CODE: generate HTTP Content-Type response header; output to stdout
System.out.println("Content-type: " + content);
// ADD_CODE: generate HTTP Content-Length response header; output to stdout
System.out.println("Content-length: " + numOfBytes);
System.out.println("");
// send file content
outToClient.write(fileInBytes, 0, numOfBytes);
inFile.close();
}
} // end else (file found case)
// close connectionSocket
connectionSocket.close();
} // end of generateResponse
}
public final class ThreadHTTPServer {
public static int serverPort = 2555; // default port CHANGE THIS
public static String http_root_path = "C:\\wamp\\www\\test"; // rooted default path in your mathlab area
private static boolean isNum(String S){
//Check wether or not the string is a number
try {
double d = Double.parseDouble(S);
}
catch(NumberFormatException e){
return false;
}
return true;
}
public static void main(String args[]) throws Exception {
// process command-line options
if (args.length >= 1 && isNum(args[0])){
serverPort = Integer.parseInt(args[0]);
}
if (args.length >= 2){
http_root_path = args[1];
}
// display error on server stdout if usage is incorrect
if (args.length > 2) {
System.out.println("usage: java HTTPServer [port_# [http_root_path]]");
System.exit(0);
}
ServerSocket serverSocket = null;
Socket clientSocket = null;
// ADD_CODE: create server socket
try
{
serverSocket = new ServerSocket(serverPort);
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + serverPort + ".");
System.exit(1);
}
// create a listening ServerSocket
System.out.println("a");
while (true) {
// accept a connection
try{
// ADD_CODE: take a waiting connection from the accepted queue
clientSocket = serverSocket.accept();
System.out.println("a");
// ADD_CODE: display on server stdout the request origin
System.out.println("Connection from "
+ clientSocket.getInetAddress() + "."
+ clientSocket.getPort());
// Construct an HTTPThread object to process the accepted connection
HTTPThread th = new HTTPThread(clientSocket, http_root_path);
// Wrap the HTTPThread in a Thread object
Thread thread = new Thread(th);
// Start the thread.
thread.start();
}catch (Exception e) {
System.out.println("ERROR" + e);
}
}
}
}