/** * HTTP Server example * * RC - 2012/2013 (LEI - FCT/UNL) * */ import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class HTTPServer { static final int PORT = 8080 ; /** * processHTTPrequest - handle one HTTP request * * @param in - stream from client * @param out - stream to client */ private static void processHTTPrequest(InputStream in, OutputStream out) { try { String request = HTTPUtilities.readLine( in ); System.out.println( "received: "+request ); String[] requestParts = HTTPUtilities.parseHttpRequest(request); // ignora-se o resto da mensagem HTTP while ( !HTTPUtilities.readLine( in ).equals("") ) ; // tratamento do pedido if( requestParts[0].equalsIgnoreCase("GET") ) { // requestParts[1] == requested file // TODO: handle request } else { // ignore other requests dumpStream (errorMessageStream(),out); } } catch (IOException e) { System.err.println(e.getMessage()); } } /** * Copia o conteudo do stream in para o stream out */ static void dumpStream( InputStream in, OutputStream out) throws IOException { byte[] arr = new byte[1024]; for( ;;) { int n = in.read( arr); if( n == -1) break; out.write( arr, 0, n); } } /** * Devolve um input stream com o conteudo dos headers e HTML que pode ser usado como * resposta em caso de erro. */ static InputStream errorMessageStream() { final String errorPage = "Request Not Supported" ; StringBuilder reply = new StringBuilder("HTTP/1.0 501 Not Implemented\r\n"); int length = errorPage.length(); reply.append("Content-Length: "+String.valueOf(length)+"\r\n\r\n"); reply.append( errorPage ); return new ByteArrayInputStream( reply.toString().getBytes()); } /** * MAIN - accept and handle client connections * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket( PORT ); for (;;) { System.out.println("Server ready at "+PORT); Socket clientS = ss.accept(); InputStream in = clientS.getInputStream(); OutputStream out = clientS.getOutputStream(); processHTTPrequest( in, out ); clientS.close(); } } }