这个简单的Web服务器会有以下三个类:
*HttpServer
*Request
*Response
应用程序的入口在HttpServer类中,main()
方法创建一个HttpServer实例,然后调用其await()方法,顾名思义,await()
方法会在指定端口上等待HTTP请求,对其进行处理,然后发送响应信息回客户端,在接收到关闭命令前,它会保持等待状态。
该应用程序仅发送位于指定目录的静态资源的请求,如html文件和图像,它也可以将传入到的http请求字节流显示到控制台,但是,它并不发送任何头信息到浏览器,如日期或者cookies等。
下面为这几个类的源码
Request:
package cn.com.server; import java.io.InputStream; public class Request { private InputStream input; private String uri; public Request(InputStream input){ this.input=input; } public void parse(){ //Read a set of characters from the socket StringBuffer request=new StringBuffer(2048); int i; byte[] buffer=new byte[2048]; try { i=input.read(buffer); } catch (Exception e) { e.printStackTrace(); i=-1; } for (int j=0;j<i;j++){ request.append((char)buffer[j]); } System.out.print(request.toString()); uri=parseUri(request.toString()); } public String parseUri(String requestString){ int index1,index2; index1=requestString.indexOf(" "); if(index1!=-1){ index2=requestString.indexOf(" ",index1+1); if(index2>index1){ return requestString.substring(index1+1,index2); } } return null; } public String getUri(){ return this.uri; } }
Request类表示一个HTTP请求,可以传递InputStream对象来创建Request对象,可以调用InputStream对象中的read()
方法来读取HTTP请求的原始数据。
上述源码中的parse()
方法用于解析Http请求的原始数据,parse()方法会调用私有方法parseUrI()
来解析HTTP请求的URI,除此之外,并没有做太多的工作,parseUri()
方法将URI存储在变量uri中,调用公共方法getUri()
会返回请求的uri。
Response:
Response对象在HttpServer类的await()
方法中通过传入套接字中获取的OutputStream来创建。
Response类有两个公共方法:setRequest()
和sendStaticResource()
,setRequest()
方法会接收一个Request对象为参数,sendStaticResource()
方法用于发送一个静态资源到浏览器,如Html文件。
HttpServer:
这个类表示一个Web服务器,这个Web服务器可以处理对指定目录的静态资源的请求,该目录包括由公有静态变量final WEB_ROOT指明的目录及其所有子目录。
现在在webroot中创建一个html页面,命名为index.html,源码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
现在启动该WEB服务器,并请求index.html静态页面。