Httpserveri näide

Allikas: Lambda
/*

Code Sample 1: HttpServer.java

See 
http://developer.java.sun.com/developer/technicalArticles/Security/secureinternet/
for this server and the https version of the server

To experiment with the HttpServer class:

   1. Copy HttpServer and save it in a file called HttpServer.java in a directory of your choice.
   2. Compile the HttpServer.java using javac.
   3. Create some sample HTML files including "index.html", which is the default document served in this example
   4. Run the HttpServer. The server runs on port 8080.
   5. Open a web browser and make a request such as http://localhost:8080 or http://127.0.0.1:8080/index.html. 
*/

 

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

/** 
 * This class implements a multithreaded simple HTTP 
 * server that supports the GET request method.
 * It listens on port 44, waits client requests, and 
 * serves documents.
 */

public class HttpServer {
   // The port number which the server 
   // will be listening on
   public static final int HTTP_PORT = 8080;

   public ServerSocket getServer() throws Exception {
      return new ServerSocket(HTTP_PORT);
   }

   // multi-threading -- create a new connection 
   // for each request
   public void run() {
      ServerSocket listen;
      try {
         listen = getServer();
         while(true) {
            Socket client = listen.accept();
            ProcessConnection cc = new 
              ProcessConnection(client);
         }
      } catch(Exception e) {
         System.out.println("Exception:  "+e.getMessage());
      }
   }

   // main program
   public static void main(String argv[]) throws 
     Exception {
      HttpServer httpserver = new HttpServer();
      httpserver.run();
   }
}


class ProcessConnection extends Thread {
   Socket client;
   BufferedReader is;
   DataOutputStream os;
   
   public ProcessConnection(Socket s) { // constructor
      client = s;
      try {
         is = new BufferedReader(new InputStreamReader
           (client.getInputStream()));
         os = new DataOutputStream(client.getOutputStream());
      } catch (IOException e) {
         System.out.println("Exception: "+e.getMessage());
      }
      this.start(); // Thread starts here...this start() will call run()
   }
 
   public void run() {
      try {
         // get a request and parse it.
         String request = is.readLine();
         System.out.println( "Request: "+request );
         StringTokenizer st = new StringTokenizer( request );
            if ( (st.countTokens() >= 2) && 
              st.nextToken().equals("GET") ) {
               if ( (request = 
                 st.nextToken()).startsWith("/") )
                  request = request.substring( 1 );
               if ( request.equals("") )
                  request = request + "index.html";
               File f = new File(request);
               shipDocument(os, f);
            } else {
               os.writeBytes( "400 Bad Request" );
            } 
            client.close();
      } catch (Exception e) {
         System.out.println("Exception: " + 
           e.getMessage());
      } 
   }

  /**
   * Read the requested file and ships it 
   * to the browser if found.
   */
   public static void shipDocument(DataOutputStream out, 
     File f) throws Exception {
       try {
          DataInputStream in = new 
            DataInputStream(new FileInputStream(f));
          int len = (int) f.length();
          byte[] buf = new byte[len];
          in.readFully(buf);
          in.close();
          out.writeBytes("HTTP/1.0 200 OK\r\n");
          out.writeBytes("Content-Length: " + 
            f.length() +"\r\n");
          out.writeBytes("Content-Type: text/html\r\n\r\n");
          out.write(buf);
          out.flush();
       } catch (Exception e) {
          out.writeBytes("<html><head><title>error</title></head><body>\r\n\r\n");
          out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
          out.writeBytes("Content-Type: text/html\r\n\r\n");
          out.writeBytes("</body></html>");
          out.flush();
       } finally {
          out.close();
       }
   }
}