Recently, I wrote an spike, implementing a minimal Http Server in Java. It’s naive, and it don’t implement all the protocol: only the minimal GET.
The code:
package com.ajlopez; import java.io.*; import java.net.*; public class HttpServer { public static void main(String[] args) { int port; ServerSocket serversocket; port = Integer.parseInt(args[0]); String rootpath = args[1]; try { serversocket = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); return; } while (true) { try { Socket socket = serversocket.accept(); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); String line = reader.readLine(); String [] words = line.split(" "); System.out.println(line); InputStream stream = new FileInputStream(rootpath + words[1]); OutputStream output = socket.getOutputStream(); byte [] buffer = new byte[4096]; int nbytes; while ((nbytes = stream.read(buffer))!=-1) output.write(buffer,0,nbytes); output.close(); stream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }It receives two arguments: the port and the root directory. You can try
java com.ajlopez.HttpServer 10000 c:\apache-tomcat-6.0.18\webapps\docs
and enter
http://localhost:10000/index.html
(don’t forget the index.html) and you get:
![]()
It’s toy code, but it works
![]()
You can get it from pastie:
or download from my AjCodeKatas google code:
http://code.google.com/p/ajcodekatas/source/browse/#svn/trunk/Spikes/MinimalHttpServer
I could improve it: separate concerns, add multithreading, etc.
Keep tuned!
Angel “Java” Lopez
http://www.ajlopez.com
[...] A Minimal Http Server in Java [...]
Pingback by A Minimal Http Server in C# « Angel “Java” Lopez on Blog — February 1, 2011 @ 10:03 am
[...] A Minimal Http Server in Java [...]
Pingback by PythonSharp (1) A minimal Web Server « Angel ”Java” Lopez on Blog — December 7, 2012 @ 4:52 pm
Hi! I just wanted to ask if you ever have any
trouble with hackers? My last blog (wordpress) was hacked and I ended
up losing a few months of hard work due to no backup.
Do you have any methods to protect against hackers?
Comment by gamblers — April 23, 2013 @ 11:07 am