-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServerThread.java
More file actions
82 lines (68 loc) · 2.75 KB
/
Copy pathHttpServerThread.java
File metadata and controls
82 lines (68 loc) · 2.75 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
package httpserver;
import java.net.*;
import java.io.*;
public class HttpServerThread extends Thread {
private Socket socket = null;
private RequestHandler handler = null;
private long connectionCounter;
public HttpServerThread(Socket socket, RequestHandler handler, long connectionCounter) {
super("HttpServerThread");
this.socket = socket;
this.handler = handler;
this.connectionCounter = connectionCounter;
}
private void cleanUp() throws IOException {
this.socket.close();
}
private void outputRequest(HttpRequest request) {
System.out.println(request.toString());
for (String headerName: request.getHeaderNames()) {
String header = request.getHeader(headerName);
System.out.println(String.format("%1s: %2s", headerName, header));
}
}
public void run() {
try {
// Add a few extra seconds.
socket.setSoTimeout((HttpServer.DEFAULT_TIMEOUT + 5) * 1000 );
OutputStream socketOut = socket.getOutputStream();
BufferedReader socketIn = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
HttpRequest request = null;
HttpResponse response = null;
do {
try {
request = HttpRequest.fromReader(socketIn);
response = handler.handle(request);
} catch (HttpError he) {
response = new StatusResponse(he.status);
} catch (NoRequestException | java.net.SocketTimeoutException nre) {
// No request found, send no response and close the connection.
response = null;
} catch (RuntimeException re) {
HttpStatus serverError = HttpStatus.ServerError();
serverError.setDetail(re.toString());
response = new StatusResponse(serverError);
re.printStackTrace();
}
if (response != null) {
response.write(socketOut);
socketOut.flush();
// Log request to stdout
System.out.println(
String.format("[%1$5d][%2$s][%3$s]",
connectionCounter, request.toString(), response.toString()
));
}
} while (response != null && response.isPersistent());
// Clean up
socketOut.close();
socketIn.close();
socket.close();
} catch (java.net.SocketException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}