Skip to content

Instantly share code, notes, and snippets.

@aleung
Created November 8, 2011 13:47
Show Gist options
  • Save aleung/1347769 to your computer and use it in GitHub Desktop.
Save aleung/1347769 to your computer and use it in GitHub Desktop.
Tiny HTTP Server by Java, only supports GET method.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
public class HttpServer {
public static void main(String args[]) {
int port;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
port = 80;
}
String root;
try {
root = args[1];
} catch (Exception e) {
root = "../";
}
try {
ServerSocket server_socket = new ServerSocket(port);
System.out.println("HttpServer running on port "
+ server_socket.getLocalPort() + ", root directory is " + root);
// server infinite loop
while (true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted "
+ socket.getInetAddress() + ":" + socket.getPort());
// Construct handler to process the HTTP request message.
try {
HttpRequestHandler request = new HttpRequestHandler(socket, root);
// Create a new thread to process the request.
Thread thread = new Thread(request);
thread.start();
} catch (Exception e) {
System.out.println(e);
}
}
} catch (IOException e) {
System.out.println(e);
}
}
}
class HttpRequestHandler implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
InputStream input;
OutputStream output;
BufferedReader br;
private String root;
public HttpRequestHandler(Socket socket, String root) throws Exception {
this.root = root;
this.socket = socket;
this.input = socket.getInputStream();
this.output = socket.getOutputStream();
this.br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
}
public void run() {
try {
processRequest();
} catch (Exception e) {
e.printStackTrace();
}
}
private void processRequest() throws Exception {
while (true) {
String headerLine = br.readLine();
System.out.println(">>>Request");
System.out.println(headerLine);
if (headerLine.equals(CRLF) || headerLine.equals(""))
break;
StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();
if (temp.equals("GET")) {
String serverLine = "Server: Simple Java Http Server";
String statusLine = null;
String contentTypeLine = "text/html";
String entityBody = null;
String contentLengthLine = "";
FileInputStream fis = null;
boolean fileExists = false;
String requestedPath = s.nextToken();
if (requestedPath.equals("/")) {
requestedPath = "";
}
String fileName = root + requestedPath;
System.out.println("===Debug");
System.out.println(fileName);
File file = new File(fileName);
if (!file.exists()) {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
entityBody = "<HTML>"
+ "<HEAD><TITLE>404 Not Found</TITLE></HEAD>"
+ "<BODY>404 Not Found"
+ "<br>usage:http://yourHostName:port/"
+ "fileName.html</BODY></HTML>";
} else {
statusLine = "HTTP/1.0 200 OK" + CRLF;
if (file.isDirectory()) {
String[] files = file.list();
entityBody = "<HTML><HEAD><TITLE>" + file.getPath()
+ "</TITLE></HEAD><BODY><UL>";
for (String entry : files) {
entityBody += "<LI><a href='" + requestedPath + "/" + entry + "'>"
+ entry +"</a></LI>";
}
entityBody += "</UL></BODY></HTML>";
} else {
try {
fis = new FileInputStream(file);
fileExists = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
contentLengthLine = "Content-Length: "
+ (new Integer(fis.available())).toString() + CRLF;
}
}
if (!fileExists) {
contentLengthLine = "Content-Length: "
+ (new Integer(entityBody.getBytes().length)).toString() + CRLF;
}
System.out.println("<<<Response");
output.write(statusLine.getBytes());
System.out.println(statusLine);
output.write(serverLine.getBytes());
System.out.println(serverLine);
output.write(contentTypeLine.getBytes());
System.out.println(contentTypeLine);
output.write(contentLengthLine.getBytes());
System.out.println(contentLengthLine);
// Send a blank line to indicate the end of the header lines.
output.write(CRLF.getBytes());
System.out.println(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, output);
fis.close();
} else {
output.write(entityBody.getBytes());
System.out.println(entityBody);
}
}
}
try {
output.close();
br.close();
socket.close();
} catch (Exception e) {
}
}
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")
|| fileName.endsWith(".txt")) {
return "text/html";
} else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
return "image/jpeg";
} else if (fileName.endsWith(".gif")) {
return "image/gif";
} else {
return "application/octet-stream";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment