Un servidor Http mínimo en Java

Published on Author lopezLeave a comment

Hace unos días, escribí un spike rápido, implementando un servidor HTTP mínimo en Java. Es código ingenuo, y que no implementa todo el protocolo, apenas parsea una línea de verbo GET.

El código:

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();
	    }
	}
    }
}

Recibe dos argumentos: el puerto y el directorio raíz. Pueden probar:

java com.ajlopez.HttpServer 10000 c:\apache-tomcat-6.0.18\webapps\docs

e ingresar

http://localhost:10000/index.html

(no se olviden de agregar index.html) y van a tener:

Es código “de juguete”, pero funciona! 😉

Pueden tomar el código del pastie:

http://pastie.org/1305444

o bajarlo del proyecto AjCodeKatas google code:

http://code.google.com/p/ajcodekatas/source/browse/#svn/trunk/Spikes/MinimalHttpServer

Podría mejorarlo: nuevas clases, separación de “concerns”, multithreading, un pool de thread fijos preparados para atender múltiples clientes, etc…

Nos leemos!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

Leave a Reply

Your email address will not be published. Required fields are marked *