-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHTTPServer.java
52 lines (39 loc) · 1.47 KB
/
HTTPServer.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
package httpd.v2;
import java.io.PrintStream;
import java.net.Socket;
public abstract class HTTPServer extends Thread {
protected static final PrintStream log = System.out;
protected Socket client;
public HTTPServer(Socket client) {
this.client = client;
}
protected abstract void doRequest(RequestContext req, ResponseContext res) throws Exception;
public void run() {
final String clientAddress = String.format("%s:%d", client.getInetAddress(), client.getPort());
log.printf("Connected to %s\n", clientAddress);
try (Socket client = this.client) {
RequestContext request = null;
ResponseContext response = null;
try {
request = new RequestContext(client.getInputStream());
response = new ResponseContext(client.getOutputStream());
request.processRequest(response);
doRequest(request, response);
} catch (Exception err) {
log.println(err.getMessage());
response.setStatus(500);
}
if (response.getStatus() != 200 && response.getResponseText().isEmpty()) {
response.out.println(response.getStatusText());
}
response.headers.put("Content-Length", response.getResponseText().getBytes().length);
response.send(!request.method.equals("HEAD"));
request.req.close();
response.res.close();
} catch (Exception e) {
log.println(e);
} finally {
log.printf("Disconnected from %s\n", clientAddress);
}
}
}