2012年7月29日 星期日

JAVA Httpd Server (with thread)

neotestserver.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class neotestserver{
  public static void main(String args[]) {
    int port;
    ServerSocket server_socket;
    try {
      port = Integer.parseInt(args[0]);
    } catch (Exception e) {
      port = 2222;
    }
    try {
      server_socket = new ServerSocket(port);
      System.out.println("Web伺服器監聽port:"
          + server_socket.getLocalPort());

      // server infinite loop
      while (true) {
        Socket socket = server_socket.accept();
        System.out.println("偵測新的連線在" +socket.getInetAddress() + ":" + socket.getPort());
        try {
          httpRequestHandler request = new httpRequestHandler(socket);
          Thread thread = new Thread(request);
          thread.start();
        } catch (Exception e) {
          System.out.println(e);
        }
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}

class httpRequestHandler implements Runnable {
  Socket socket;
  InputStream input;
  OutputStream output;
  BufferedReader br;

  public httpRequestHandler(Socket socket) throws Exception {
    this.socket = socket;
    this.input = socket.getInputStream();
    this.output = socket.getOutputStream();
    this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  }
  
  public void run() {
    try {
    	while (true) {
    	      String headerLine = br.readLine();
    	      System.out.println(headerLine);
    	      if (headerLine.equals("\r\n") || headerLine.equals(""))
    	        break;
    	      StringTokenizer s = new StringTokenizer(headerLine);
    	      String temp = s.nextToken();
    	      if (temp.equals("GET")) {
    	    	  String fileName = s.nextToken();  //GET之後是fileName
    	    	  fileName = "." + fileName;		  //fileName前面記得加上"."
    	    	  FileInputStream fis = null;
    	    	  boolean fileExists = true;
    	    	  try {
    	    		  fis = new FileInputStream(fileName);
    	    	  } catch (FileNotFoundException e) {
    	    		  fileExists = false;
    	    	  }
    	    	  String urlstr ="";
    	    	  if (fileExists) {
    	    		  urlstr = "HTTP/1.0 200 OK\r\n" + "Content-type: " + contentType(fileName) + "\r\n" + "Content-Length: " + (new Integer(fis.available())).toString() + "\r\n" + "\r\n";
    	        	  //填上fileName的內容
    	    		  output.write(urlstr.getBytes());
    	    		  byte[] buffer = new byte[1024];
    	    		  int bytes = 0;
    	    		  while ((bytes = fis.read(buffer)) != -1) {
    	    			  output.write(buffer, 0, bytes);
    	    		  }
    	    		  socket.close();
    	    	  } else {
    	    		  urlstr = "HTTP/1.0 404 Not Found\r\n" + "text/html\r\n\r\n" + "<HTML> <HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY>404 Not Found<br>usage:http://yourHostName:port/fileName.html</BODY></HTML>\r\n";
    	    		  output.write(urlstr.getBytes());
    	    		  socket.close();
    	    	  }   
    	      }
    	    }    
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  
  private static String contentType(String fileName) {
    if (fileName.endsWith(".htm") || fileName.endsWith(".html")
        || fileName.endsWith(".txt")) {
      return "text/html";
    } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
      return "image/jpeg";
    } else if (fileName.endsWith(".gif")) {
      return "image/gif";
    } else {
      return "application/octet-stream";
    }
  }
}     

沒有留言:

張貼留言