-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.java
67 lines (56 loc) · 2.29 KB
/
Server.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
// A simple web server using Java's built-in HttpServer
// Examples from https://dzone.com/articles/simple-http-server-in-java were useful references
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
interface URLHandler {
String handleRequest(URI url);
}
class ServerHttpHandler implements HttpHandler {
URLHandler handler;
ServerHttpHandler(URLHandler handler) {
this.handler = handler;
}
public void handle(final HttpExchange exchange) throws IOException {
// form return body after being handled by program
try {
URI uri = exchange.getRequestURI();
try(FileWriter fw = new FileWriter("session.log", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
out.println(uri.toString());
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
String ret = handler.handleRequest(uri);
// form the return string and write it on the browser
exchange.sendResponseHeaders(200, ret.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(ret.getBytes());
os.close();
} catch(Exception e) {
String response = e.toString();
exchange.sendResponseHeaders(500, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
public class Server {
public static void start(int port, URLHandler handler) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
//create request entrypoint
server.createContext("/", new ServerHttpHandler(handler));
//start the server
server.start();
System.out.println("Server Started! Visit http://localhost:" + port + " to visit.");
}
}