To program a web or HTTP server from nothing could be very difficult. It’s gonna to take you to write thousands of source instructions. The HTTP protocol it self is pretty to understand but it complicated to implement them in programming language. It involves a lot of parsing and need a lot of understanding how the HTTP requests and HTTP responses work together.
In Java SDK, you can use the HttpServer class in com.sun.net.httpserver.HttpServer package. It is pretty simple to use HttpServer to create a simple web server, what you need to do is to implement a HttpHandler for a specific URL/context.
Below is a sample of simple HTTP server that send files sit on the web server to client when user request the file via web browser.
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import com.sun.net.httpserver.*;
public class TimeServer
{
private static int SERVER_PORT = 3000;
private class FileDownloadHandler
implements HttpHandler
{
public void
handle (
HttpExchange httpExc)
throws IOException
{
String filename;
String contentType;
OutputStream out;
long rspLen;
int len;
byte[] buffer;
File file;
FileInputStream in;
filename = httpExc.getRequestURI ().getPath ();
if (filename == null || filename.isEmpty ())
filename = "TimeClient.html";
if (filename.startsWith ("/"))
filename = filename.substring (1);
file = new File (filename);
if (!file.isFile ()) {
sendResponse (httpExc, 404,
"Not found: " + filename + "");
System.err.println ("Not found: " + filename);
return;
}
in = null;
buffer = new byte[4096];
out = httpExc.getResponseBody ();
rspLen = file.length ();
httpExc.sendResponseHeaders (200, rspLen);
try {
in = new FileInputStream (file);
} catch (IOException e) {
sendResponse (httpExc, 500,
"Error reading file: " +
filename + "");
System.err.println ("Error reading file: " + filename);
return;
}
try {
while ((len = in.read(buffer)) != -1)
out.write (buffer, 0, len);
} catch (IOException e) {
sendResponse (httpExc, 500,
"Error writing file: " +
filename + "");
System.err.println ("Error writing file: " + filename);
}
try {
in.close ();
} catch (IOException e) {
// DO NOTHING
}
try {
out.close ();
} catch (IOException e) {
// DO NOTHING
}
}
}
public void
sendResponse (
HttpExchange httpExc,
int responseCode, // Response code
String responseBody) // Response body
throws IOException
{
byte[] data; // Data
OutputStream out; // Output stream
data = responseBody.getBytes ();
httpExc.sendResponseHeaders (responseCode, data.length);
out = httpExc.getResponseBody ();
out.write (data, 0, data.length);
out.close ();
}
public void
main ()
throws IOException
{
HttpServer server;
// Create and start the http server instance
server = HttpServer.create (new InetSocketAddress(SERVER_PORT), 0);
server.createContext ("/", new FileDownloadHandler());
server.setExecutor (null);
server.start ();
}
public static void
main (
String[] args)
throws Exception
{
(new WebServer()).main ();
}
}
The example above is just a very simple web server that allow user to download files. If you need a more comprehensive one, you may want to look into the packages in J2EE (Servlet and JSP).
Leave a Reply