Beispiel: HTTP-Server mit CGI

class CgiHttp

import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class CgiHttp
{ // Liest die Parameter und startet den Server-Thread
 String docroot = "."; // Root des Server-Dateisystems
 String indexfile = "index.html";
 int port = 0;  // Der Port, an dem der Server warten soll
 String cgiprog; // Cgi-Interpreter
 String cgidir = ".";  // Verzeichnis der Cgi-Dateisystems

 public static void main(String args[])
 {
  try
  {
   new CgiHttp(args[0]);
  }
  catch (ArrayIndexOutOfBoundsException e)
  {
   System.err.println("Parameter fehlt! (Konfigurations-Datei)");
  }
  catch (IOException e)
  {
   System.err.println("Konnte Konfigurations-Datei nicht lesen.");
  }
// Konsole auflassen bis Eingabe
  System.out.println("Beenden mit <ENTER>.");
  try
  { System.in.read(); }
  catch (IOException e) {}
 
  System.exit(0);
}

 public CgiHttp(String file) throws IOException
 {
  System.out.println( "Starte Server ..." );
  ReadConfig(file);
// Server starten
  try
  {
   new HttpServer(docroot, indexfile, port, cgiprog, cgidir).start();
  }
  catch (Exception e)
  { System.out.println( "... Error. Exception: " +e ); }
// Rueckmeldung
  System.out.println( "... Ok." );
  System.out.println("docroot: " + docroot);
  System.out.println("indexfile: " + indexfile);
  System.out.println("port: " + port);
  System.out.println("cgiprog: " + cgiprog);
  System.out.println("cgidir: " + cgidir);
 }

 void ReadConfig(String file) throws IOException
 {
  String get, value;
  FileInputStream fis = new FileInputStream(file);
  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  while ((get = br.readLine()) != null)
  {
   value = get.substring(get.indexOf('=')+1,get.length());
   if (get.startsWith("PORT"))
   {
    port = Integer.parseInt(value);
    if (port < 0 || port > 65535)
     port = 0;
   }
   else if (get.startsWith("DOCROOT")) docroot = value;
   else if (get.startsWith("INDEXFILE")) indexfile = value;
   else if (get.startsWith("CGIPROG")) cgiprog = value;
   else if (get.startsWith("CGIDIR")) cgidir = value;
  }
  fis.close();
  br.close();
 }
 
 

}