This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Server.java
53 lines (45 loc) · 1.83 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
// 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 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 {
String ret = handler.handleRequest(exchange.getRequestURI());
// 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.");
}
}