import java.io.* ;
import java.net.* ;
// This "Web server" will return HTML files (only) that it finds in
// the directory where it is run (or its subdirectories).
// You must specify port 8080 in the URL entered into your browser.
public class TrivialHTTPD {
public static void main(String [] args) throws Exception {
ServerSocket server = new ServerSocket(8080);
while (true) {
Socket sock = server.accept() ;
BufferedReader in =
new BufferedReader(new InputStreamReader(sock.getInputStream()));
String req = in.readLine();
System.out.println(req) ; // debug
readRemainder(in) ;
System.out.println("Got request header: " + req) ;
String fileName = getFileName(req) ;
DataOutputStream out =
new DataOutputStream(sock.getOutputStream());
byte [] fileContents = readBytes("." + fileName) ;
if(getExtension(fileName).equals("html") && fileContents != null) {
out.writeBytes("HTTP/1.0 200 OK\r\n");
out.writeBytes("Content-Length: " + fileContents.length + "\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.write(fileContents);
} else
out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
out.close();
}
}
/**
* Skips over remaining lines of HTTP header, till empty line.
*/
static void readRemainder(BufferedReader in) throws IOException {
while(true) {
String line = in.readLine();
System.out.println(line) ; // debug
if(line == null || line.length() == 0 ||
line.charAt(0) == '\r' || line.charAt(0) == '\n') break ;
}
}
/**
* Gets the file name from the method field.
*/
static String getFileName(String header) {
String result = header.substring(4); // Strip off "GET "
int i = result.indexOf(' ');
return result.substring(0, i); // Strip off protocol version
}
/**
* Naively extracts extension from a filename
*/
static String getExtension(String fileName) {
int j = fileName.indexOf('.');
return fileName.substring(j + 1); // file extension
}
/**
* Reads all bytes in a file.
*/
static byte [] readBytes(String name) {
try {
File f = new File(name) ;
DataInputStream din =
new DataInputStream(new FileInputStream(f));
byte[] bytes = new byte[(int) f.length()];
din.readFully(bytes);
din.close();
return bytes ;
} catch (IOException e) {
return null ;
}
}
}