`
VerRan
  • 浏览: 456917 次
  • 性别: Icon_minigender_1
  • 来自: 陕西.西安
社区版块
存档分类
最新评论

how tomcat works- implemention of a simple Server

阅读更多
1. 服务器类
建立ServerSoke,作为request和response的中枢
  1. package ex01.pyrmont;   
  2.   
  3. import java.net.Socket;   
  4. import java.net.ServerSocket;   
  5. import java.net.InetAddress;   
  6. import java.io.InputStream;   
  7. import java.io.OutputStream;   
  8. import java.io.IOException;   
  9. import java.io.File;   
  10.   
  11. public class HttpServer {   
  12.   
  13.   /** WEB_ROOT is the directory where our HTML and other files reside.  
  14.    *  For this package, WEB_ROOT is the "webroot" directory under the working  
  15.    *  directory.  
  16.    *  The working directory is the location in the file system  
  17.    *  from where the java command was invoked.  
  18.    */  
  19.   public static final String WEB_ROOT =   
  20.     System.getProperty("user.dir") + File.separator  + "webroot";   
  21.   
  22.   // shutdown command   
  23.   private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";   
  24.   
  25.   // the shutdown command received   
  26.   private boolean shutdown = false;   
  27.   
  28.   public static void main(String[] args) {   
  29.     HttpServer server = new HttpServer();   
  30.     server.await();   
  31.   }   
  32.   
  33.   public void await() {   
  34.     ServerSocket serverSocket = null;   
  35.     int port = 8080;   
  36.     try {   
  37.       serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));   
  38.     }   
  39.     catch (IOException e) {   
  40.       e.printStackTrace();   
  41.       System.exit(1);   
  42.     }   
  43.   
  44.     // Loop waiting for a request   
  45.     while (!shutdown) {   
  46.       Socket socket = null;   
  47.       InputStream input = null;   
  48.       OutputStream output = null;   
  49.       try {   
  50.         socket = serverSocket.accept();   
  51.         input = socket.getInputStream();   
  52.         output = socket.getOutputStream();   
  53.   
  54.         // create Request object and parse   
  55.         Request request = new Request(input);   
  56.         request.parse();   
  57.   
  58.         // create Response object   
  59.         Response response = new Response(output);   
  60.         response.setRequest(request);   
  61.         response.sendStaticResource();   
  62.   
  63.         // Close the socket   
  64.         socket.close();   
  65.   
  66.         //check if the previous URI is a shutdown command   
  67.         shutdown = request.getUri().equals(SHUTDOWN_COMMAND);   
  68.       }   
  69.       catch (Exception e) {   
  70.         e.printStackTrace();   
  71.         continue;   
  72.       }   
  73.     }   
  74.   }   
  75. }   

2. 处理请求的类
  1. package ex01.pyrmont;   
  2.   
  3. import java.io.InputStream;   
  4. import java.io.IOException;   
  5.   
  6. public class Request {   
  7.   
  8.   private InputStream input;   
  9.   private String uri;   
  10.   
  11.   public Request(InputStream input) {   
  12.     this.input = input;   
  13.   }   
  14.   
  15.   public void parse() {   
  16.     // Read a set of characters from the socket   
  17.     StringBuffer request = new StringBuffer(2048);   
  18.     int i;   
  19.     byte[] buffer = new byte[2048];   
  20.     try {   
  21.       i = input.read(buffer);//把输入流中的信息读入字节数组中....   
  22.     }   
  23.     catch (IOException e) {   
  24.       e.printStackTrace();   
  25.       i = -1;   
  26.     }   
  27.     for (int j=0; j<i; j++) {   
  28.       request.append((char) buffer[j]);   
  29.     }   
  30.     System.out.print(request.toString());   
  31.     uri = parseUri(request.toString());   
  32.   }   
  33.   
  34.   private String parseUri(String requestString) {   
  35.     int index1, index2;   
  36.     index1 = requestString.indexOf(' ');//获得出现第一个空格的索引值   
  37.     if (index1 != -1) {   
  38.       index2 = requestString.indexOf(' ', index1 + 1);//获得指定索引后第一个出现空格的索引   
  39.       if (index2 > index1)   
  40.         return requestString.substring(index1 + 1, index2);//返回空格之间的值   
  41.     }   
  42.     return null;   
  43.   }   
  44.   
  45.   public String getUri() {   
  46.     return uri;   
  47.   }   
  48.   
  49. }  

3. 处理响应的类
  1. package ex01.pyrmont;   
  2.   
  3. import java.io.OutputStream;   
  4. import java.io.IOException;   
  5. import java.io.FileInputStream;   
  6. import java.io.File;   
  7.   
  8. /*  
  9.   HTTP Response = Status-Line  
  10.     *(( general-header | response-header | entity-header ) CRLF)  
  11.     CRLF  
  12.     [ message-body ]  
  13.     Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF  
  14. */  
  15.   
  16. public class Response {   
  17.   
  18.   private static final int BUFFER_SIZE = 1024;   
  19.   Request request;   
  20.   OutputStream output;   
  21.   
  22.   public Response(OutputStream output) {   
  23.     this.output = output;   
  24.   }   
  25.   
  26.   public void setRequest(Request request) {   
  27.     this.request = request;   
  28.   }   
  29.   
  30.   public void sendStaticResource() throws IOException {   
  31.     byte[] bytes = new byte[BUFFER_SIZE];   
  32.     FileInputStream fis = null;   
  33.     try {   
  34.       File file = new File(HttpServer.WEB_ROOT, request.getUri());   
  35.       //System.out.print("+++++++++++++++"+request.getUri());   
  36.       String tt=request.getUri();   
  37.      byte[] xx=new byte[30];   
  38.       xx=tt.getBytes();   
  39.      output.write(xx,0,xx.length);   
  40.       if (file.exists()) {   
  41.         fis = new FileInputStream(file);   
  42.         int ch = fis.read(bytes, 0, BUFFER_SIZE);   
  43.         while (ch!=-1) {   
  44.           output.write(bytes, 0, ch);   
  45.              
  46.           ch = fis.read(bytes, 0, BUFFER_SIZE);   
  47.         }   
  48.       }   
  49.       else {   
  50.         // file not found   
  51.         String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +   
  52.           "Content-Type: text/html\r\n" +   
  53.           "Content-Length: 23\r\n" +   
  54.           "\r\n" +   
  55.           "<h1>File Not Foundererewrwerwer</h1>";   
  56.         output.write(errorMessage.getBytes());   
  57.       }   
  58.     }   
  59.     catch (Exception e) {   
  60.       // thrown if cannot instantiate a File object   
  61.       System.out.println(e.toString() );   
  62.     }   
  63.     finally {   
  64.       if (fis!=null)   
  65.         fis.close();   
  66.     }   
  67.   }   
  68. }  

4. 输出结果
访问地址:http://localhost:8080/index.html
  1. GET /index.html HTTP/1.1   
  2. Accept: */*   
  3. Accept-Language: zh-cn   
  4. UA-CPU: x86   
  5. Accept-Encoding: gzip, deflate   
  6. User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler ; .NET CLR 2.0.50727)   
  7. Host: localhost:8080   
  8. Connection: Keep-Alive  

5. 总结
这样我们就实现了一个简单的服务器,不过这里智能处理静态页面,动态页面的处理待续。。。。
分享到:
评论
1 楼 web322 2008-06-25  
太好了,正好好处理过滤输出的静态资源文件。谢谢

相关推荐

Global site tag (gtag.js) - Google Analytics