-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHTTPServer.java
More file actions
234 lines (205 loc) · 8.92 KB
/
Copy pathMyHTTPServer.java
File metadata and controls
234 lines (205 loc) · 8.92 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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package test;
import java.io.*;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;
import java.net.ServerSocket;
/**
* A simple HTTP server implementation that manages and dispatches HTTP requests
* to the appropriate servlets based on the request type and URI.
*/
public class MyHTTPServer extends Thread implements HTTPServer {
/** Concurrent map to manage servlets for GET,POST,DELETE requests. */
private ConcurrentHashMap<String, Servlet> getServlets = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, Servlet> postServlets = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, Servlet> deleteServlets = new ConcurrentHashMap<>();
/** Thread pool to handle multiple client connections concurrently. */
private ExecutorService requestHandlerPool;
/** Socket used to accept client connections. */
private ServerSocket serverSocket;
/** Flag to indicate if the server should stop accepting requests. */
private volatile boolean isServerStopped = false;
/** Port number on which the server listens for incoming connections. */
private final int port;
/** Number of threads in the thread pool for handling requests. */
private final int threadCount;
/** Default number of threads for the server */
private static final int DEFAULT_THREAD_COUNT = 4;
/**
* Constructs a new HTTP server instance with the specified port and default thread count.
*
* @param port The port number for the server to listen on.
*/
public MyHTTPServer(int port) {
this(port, DEFAULT_THREAD_COUNT);
}
/**
* Constructs a new HTTP server instance with the specified port and thread count.
*
* @param port The port number for the server to listen on.
* @param threadCount The number of threads in the thread pool.
*/
public MyHTTPServer(int port, int threadCount) {
// Initialize the thread pool with a fixed number of threads
requestHandlerPool = Executors.newFixedThreadPool(threadCount);
this.port = port;
this.threadCount = threadCount;
}
/**
* Registers a servlet to handle requests for a specific HTTP command and URI.
*
* @param httpCommand The HTTP command (e.g., GET, POST, DELETE) for which the servlet will handle requests.
* @param uri The URI that the servlet will handle.
* @param servlet The servlet instance to handle the requests.
*/
public void addServlet(String httpCommand, String uri, Servlet servlet) {
if (uri == null || servlet == null) {
return;
}
httpCommand = httpCommand.toUpperCase();
switch (httpCommand) {
case "GET":
getServlets.put(uri, servlet);
break;
case "POST":
postServlets.put(uri, servlet);
break;
case "DELETE":
deleteServlets.put(uri, servlet);
break;
}
}
/**
* Removes a servlet that handles requests for a specific HTTP command and URI.
*
* @param httpCommand The HTTP command (e.g., GET, POST, DELETE) for which the servlet was handling requests.
* @param uri The URI that the servlet was handling.
*/
public void removeServlet(String httpCommand, String uri) {
if (uri == null) {
return;
}
httpCommand = httpCommand.toUpperCase();
switch (httpCommand) {
case "GET":
getServlets.remove(uri);
break;
case "POST":
postServlets.remove(uri);
break;
case "DELETE":
deleteServlets.remove(uri);
break;
}
}
/**
* Starts the HTTP server to listen for and handle client connections.
*/
public void run() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
this.serverSocket = serverSocket;
serverSocket.setSoTimeout(1000); // Set timeout for socket accept operations
while (!isServerStopped) {
try {
// Accept a new client connection
Socket clientSocket = serverSocket.accept();
// Handle the client request in a separate thread
requestHandlerPool.submit(() -> {
try {
Thread.sleep(125); // Delay to ensure proper request reception
BufferedReader requestReader = createBufferedReader(clientSocket);
// Parse the incoming request
RequestParser.RequestInfo requestInfo = RequestParser.parseRequest(requestReader);
ConcurrentHashMap<String, Servlet> servletMap;
if (requestInfo != null) {
switch (requestInfo.getHttpCommand()) {
case "GET":
servletMap = getServlets;
break;
case "POST":
servletMap = postServlets;
break;
case "DELETE":
servletMap = deleteServlets;
break;
default:
throw new IllegalArgumentException("Unsupported HTTP command: " + requestInfo.getHttpCommand());
}
// Find the best matching servlet based on the longest URI match
String bestMatchUri = "";
Servlet matchingServlet = null;
for (Map.Entry<String, Servlet> entry : servletMap.entrySet()) {
if (requestInfo.getUri().startsWith(entry.getKey()) && entry.getKey().length() > bestMatchUri.length()) {
bestMatchUri = entry.getKey();
matchingServlet = entry.getValue();
}
}
// Handle the request using the matching servlet
if (matchingServlet != null) {
matchingServlet.handle(requestInfo, clientSocket.getOutputStream());
}
}
requestReader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
// Close the client connection
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (IOException e) {
// Handle socket accept timeout exception
if (isServerStopped) {
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Creates a BufferedReader to read from the client socket.
*
* @param clientSocket The client socket.
* @return A BufferedReader to read from the socket.
* @throws IOException If an I/O error occurs.
*/
private static BufferedReader createBufferedReader(Socket clientSocket) throws IOException {
InputStream inputStream = clientSocket.getInputStream();
int availableBytes = inputStream.available();
byte[] buffer = new byte[availableBytes];
int bytesRead = inputStream.read(buffer, 0, availableBytes);
return new BufferedReader(
new InputStreamReader(
new ByteArrayInputStream(buffer, 0, bytesRead)
)
);
}
/**
* Starts the HTTP server to begin accepting and handling requests.
*/
public void start() {
isServerStopped = false;
super.start();
}
/**
* Stops the HTTP server and shuts down the thread pool.
*/
public void close() {
isServerStopped = true;
requestHandlerPool.shutdownNow();
}
/**
* Gets the thread pool used by the server for handling client requests.
*
* @return The thread pool.
*/
public Object getThreadPool() {
return requestHandlerPool;
}
}