java实现一个简单的Web服务器

来源:互联网 发布:淘宝中秋节活动logo 编辑:程序博客网 时间:2024/04/27 20:32

Web服务器也称为超文本传输协议服务器,使用http与其客户端进行通信,基于java的web服务器会使用两个重要的类,

java.net.Socket类和java.net.ServerSocket类,并基于发送http消息进行通信。

这个简单的Web服务器会有以下三个类:

*HttpServer

*Request

*Response

应用程序的入口在HttpServer类中,main()方法创建一个HttpServer实例,然后调用其await()方法,顾名思义,await()方法会在指定端口

上等待HTTP请求,对其进行处理,然后发送响应信息回客户端,在接收到关闭命令前,它会保持等待状态。

该应用程序仅发送位于指定目录的静态资源的请求,如html文件和图像,它也可以将传入到的http请求字节流显示到控制台,但是,它并不发送

任何头信息到浏览器,如日期或者cookies等。

下面为这几个类的源码:

Request:

[java] view plaincopy
  1. package cn.com.server;  
  2.   
  3. import java.io.InputStream;  
  4.   
  5. public class Request {  
  6.     private InputStream input;  
  7.       
  8.     private String uri;  
  9.       
  10.     public Request(InputStream input){  
  11.         this.input=input;  
  12.     }  
  13.       
  14.     public void parse(){  
  15.         //Read a set of characters from the socket  
  16.         StringBuffer request=new StringBuffer(2048);  
  17.         int i;  
  18.         byte[] buffer=new byte[2048];  
  19.         try {  
  20.             i=input.read(buffer);  
  21.         } catch (Exception e) {  
  22.             e.printStackTrace();  
  23.             i=-1;  
  24.         }  
  25.         for(int j=0;j<i;j++){  
  26.             request.append((char)buffer[j]);  
  27.         }  
  28.         System.out.print(request.toString());  
  29.         uri=parseUri(request.toString());  
  30.     }  
  31.       
  32.     public String parseUri(String requestString){  
  33.         int index1,index2;  
  34.         index1=requestString.indexOf(" ");  
  35.         if(index1!=-1){  
  36.             index2=requestString.indexOf(" ",index1+1);  
  37.             if(index2>index1){  
  38.                 return requestString.substring(index1+1,index2);  
  39.             }  
  40.         }  
  41.         return null;  
  42.     }  
  43.       
  44.     public String getUri(){  
  45.         return this.uri;  
  46.     }  
  47. }  
Request类表示一个HTTP请求,可以传递InputStream对象来创建Request对象,可以调用InputStream对象中的read()方法来读取HTTP请求

的原始数据。

上述源码中的parse()方法用于解析Http请求的原始数据,parse()方法会调用私有方法parseUrI()来解析HTTP请求的URI,除此之外,并没有

做太多的工作,parseUri()方法将URI存储在变量uri中,调用公共方法getUri()会返回请求的uri。

Response:

[java] view plaincopy
  1. <span style="font-size:10px;">package cn.com.server;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.OutputStream;  
  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.     private static final int BUFFER_SIZE=1024;  
  18.     Request request;  
  19.     OutputStream output;  
  20.       
  21.     public Response(OutputStream output){  
  22.         this.output=output;  
  23.     }  
  24.       
  25.     public void setRequest(Request request){  
  26.         this.request=request;  
  27.     }  
  28.       
  29.     public void sendStaticResource()throws IOException{  
  30.         byte[] bytes=new byte[BUFFER_SIZE];  
  31.         FileInputStream fis=null;  
  32.         try {  
  33.             File file=new File(HttpServer.WEB_ROOT,request.getUri());  
  34.             if(file.exists()){  
  35.                 fis=new FileInputStream(file);  
  36.                 int ch=fis.read(bytes,0,BUFFER_SIZE);  
  37.                 while(ch!=-1){  
  38.                     output.write(bytes, 0, BUFFER_SIZE);  
  39.                     ch=fis.read(bytes, 0, BUFFER_SIZE);  
  40.                 }  
  41.             }else{  
  42.                 //file not found  
  43.                 String errorMessage="HTTP/1.1 404 File Not Found\r\n"+  
  44.                 "Content-Type:text/html\r\n"+  
  45.                 "Content-Length:23\r\n"+  
  46.                 "\r\n"+  
  47.                 "<h1>File Not Found</h1>";  
  48.                 output.write(errorMessage.getBytes());  
  49.             }  
  50.         } catch (Exception e) {  
  51.             System.out.println(e.toString());  
  52.         }finally{  
  53.             if(fis!=null){  
  54.                 fis.close();  
  55.             }  
  56.         }  
  57.     }  
  58. }</span><span style="font-size:24px;">  
  59. </span>  
Response对象在HttpServer类的await()方法中通过传入套接字中获取的OutputStream来创建。

Response类有两个公共方法:setRequest()和sendStaticResource(),setRequest()方法会接收一个Request对象为参数,sendStaticResource()

方法用于发送一个静态资源到浏览器,如Html文件。

HttpServer:

[java] view plaincopy
  1. package cn.com.server;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.net.InetAddress;  
  7. import java.net.ServerSocket;  
  8. import java.net.Socket;  
  9.   
  10. public class HttpServer {  
  11.     /** 
  12.      * WEB_ROOT is the directory where our html and other files reside. 
  13.      * For this package,WEB_ROOT is the "webroot" directory under the 
  14.      * working directory. 
  15.      * the working directory is the location in the file system 
  16.      * from where the java command was invoke. 
  17.      */  
  18.     public static final String WEB_ROOT=System.getProperty("user.dir")+File.separator+"webroot";  
  19.       
  20.     private static final String SHUTDOWN_COMMAND="/SHUTDOWN";  
  21.       
  22.     private boolean shutdown=false;  
  23.       
  24.     public static void main(String[] args) {  
  25.         HttpServer server=new HttpServer();  
  26.         server.await();  
  27.     }  
  28.       
  29.     public void await(){  
  30.         ServerSocket serverSocket=null;  
  31.         int port=8080;  
  32.         try {  
  33.             serverSocket=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));  
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.             System.exit(0);  
  37.         }  
  38.         while(!shutdown){  
  39.             Socket socket=null;  
  40.             InputStream input=null;  
  41.             OutputStream output=null;  
  42.             try {  
  43.                 socket=serverSocket.accept();  
  44.                 input=socket.getInputStream();  
  45.                 output=socket.getOutputStream();  
  46.                 //create Request object and parse  
  47.                 Request request=new Request(input);  
  48.                 request.parse();  
  49.                   
  50.                 //create Response object  
  51.                 Response response=new Response(output);  
  52.                 response.setRequest(request);  
  53.                 response.sendStaticResource();  
  54.             } catch (Exception e) {  
  55.                 e.printStackTrace();  
  56.                 continue;  
  57.             }  
  58.         }  
  59.     }  
  60. }  
这个类表示一个Web服务器,这个Web服务器可以处理对指定目录的静态资源的请求,该目录包括由公有静态变量final WEB_ROOT指明的目录及其所有子目录。

现在在webroot中创建一个html页面,命名为index.html,源码如下:

[html] view plaincopy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Insert title here</title>  
  6. </head>  
  7. <body>  
  8.     <h1>Hello World!</h1>  
  9. </body>  
  10. </html>  

现在启动该WEB服务器,并请求index.html静态页面。

所对应的控制台的输出:


如此,一个简单的http服务器便完成了。

0 0
原创粉丝点击