-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebServer.java
84 lines (76 loc) · 3.13 KB
/
WebServer.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
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class WebServer {
private static final int PORT = Integer.parseInt(Config.properties.getProperty("port"));
private static final int MAX_CONNECTIONS = Integer.parseInt(Config.properties.getProperty("maxThreads"));
public static void main(String[] args) throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(MAX_CONNECTIONS);
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
Socket clientSocket = serverSocket.accept();
executorService.submit(new ConnectionHandler(clientSocket));
}
}
}
private static class ConnectionHandler implements Runnable {
private Socket clientSocket;
public ConnectionHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
handleClientConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void handleClientConnection() throws IOException {
BufferedReader in = null;
DataOutputStream out = null;
try {
while (true) {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new DataOutputStream(clientSocket.getOutputStream());
StringBuilder requestBuilder = new StringBuilder();
String line;
while (!(line = in.readLine()).isEmpty()) {
requestBuilder.append(line).append("\r\n");
}
while (in.ready()) {
requestBuilder.append((char) in.read());
if (!in.ready()) {
requestBuilder.append("\r\n");
}
}
// they ask to print the request
System.out.println(requestBuilder);
HTTPResponseHandler httpResponseHandler = new HTTPResponseHandler();
HTTPRequest request = null;
try {
request = new HTTPRequest(requestBuilder.toString());
} catch (Exception e) {
httpResponseHandler.sendErrorResponse(400, "Bad Request", out);
}
if (request != null) {
try {
httpResponseHandler.handle(request, out);
} catch (Exception e) {
httpResponseHandler.sendErrorResponse(500, "Internal Server Error", out);
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
}