Skip to content

Instantly share code, notes, and snippets.

@ear7h
Created March 3, 2018 19:53
Show Gist options
  • Save ear7h/8c0f4d8b182838410ce3b897835b43f3 to your computer and use it in GitHub Desktop.
Save ear7h/8c0f4d8b182838410ce3b897835b43f3 to your computer and use it in GitHub Desktop.
Simple server class, has some hints at working to a file server
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.net.InetSocketAddress;
public class Server {
public static void main(String[] args) throws IOException{
//printf("Hello %s\n", "string");
HttpServer h = HttpServer.create(new InetSocketAddress(8080), 0);
h.createContext("/", new MyHandler());
h.createContext("/api/tuts/", new MyHandler());
h.setExecutor(null);
h.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String basePath = "static";
String reqFile = basePath + t.getRequestURI().getPath();
byte[] res = t.getRequestURI().getPath().getBytes();
printf("handling %s\n", t.getRequestURI());
printf("looking in file %s\n", reqFile);
t.sendResponseHeaders(200, res.length);
t.getResponseBody().write(res);
t.getResponseBody().close();
t.close();
}
}
public static void printf(String fmt, Object... args) {
System.out.printf(fmt, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment