Saturday, January 26, 2008

Smallest ever web server in Java

Suppose you are writing a server, and you want it to expose a simple web page with, say, usage statistics. In JRE 1.6 Sun has implemented an HTTP server class that makes it remarkably simple.

Here's all you need to do, and your app will start responding to your browser on a given port (I chose 8000 for this example):

import java.io.*;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.*;

class SmallestEverWebServer
implements HttpHandler {
public void handle(HttpExchange t)
throws IOException {
String response = "Hello! You asked for "
+ t.getRequestURI();
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}

public static void main(String[] args)
throws IOException {
HttpServer server = HttpServer.create(
new InetSocketAddress(8000), 0);
server.createContext("/",
new SmallestEverWebServer());
server.setExecutor(null);
server.start();

System.out.println("Server is running.");
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));

for (;;) {
System.out.print("Enter 'exit' to exit> ");
String line = in.readLine();
if (line.compareToIgnoreCase("exit") == 0)
break;
}
server.stop(0);
}
}

No comments: