基于JAVA的WEB服务器工作机制(3)完

Request

Request类代表一个HTTP请求。Socket处理客户端的通讯,将返回一个InputStream对象,通过传递该对象,可以构造一个Request类的实例。通过调用InputStream 对象的read方法来获得这个HTTP请求的原始数据(raw data)。

Request 有两个公共方法:parse 和 getUri。parse方法解释HTTP请求的原始数据。它不做很多事情----它能够利用的唯一信息只是HTTP请求的URI ,这个URI是从私有方法 parseUri.得到的。parseUri 方法保存URI 到uri 变量中,然后调用公共方法getUri来返回一个HTTP请求的URI。

为了理解parse 和 parseUri 方法是如何工作的,需要知道HTTP请求的内部结构。这个结构是在RFC2616文档中定义的。

一个HTTP请求包含三个部分:

  • 请求行(Request line)
  • 请求包头(Headers)
  • 消息体(Message body)

现在,我们仅仅只对HTTP请求的第一部分请求行(Request line)感兴趣。一个请求行由方法标记开始,后面根请求的URI和协议版本,最后由CRLF字符结束。请求行中的元素被空格字符分开。比如,使用GET方法请求的index.html文件的请求行如下:

GET /index.html HTTP/1.1 //这是一个请求行

方法parse从socket的InputStream 中读取整个字节流,该字节流是 Request 对象传递进来的,然后parse将这些字节流存储在一个缓冲区里, 在缓冲区中组装一个称为request的StringBuffer对象。

下面的Listing 1.2.显示了parse方法的用法:

Listing 1.2. The Request class' parse method

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 (IOException 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());
}

parseUri 方法从请求行那里得到URI。Listing 1.3 展示了parseUri 方法的用途。 parseUri 减缩请求中的第一个和第二个空格来获得URI。

Listing 1.3. The Request class' parseUri method

private 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;
}
Response

Response表示一个HTTP响应。它的构造函数接受一个OutputStream对象,比如下面的:

public Response(OutputStream output) {
    this.output = output;
}

Response 对象被HttpServer类的await方法构造,该方法被传递的参数是从socket那里得到的OutputStream对象。

Response类有两个公共方法: setRequestsendStaticResource. setRequest方法传递一个Request对象给Response对象。Listing 1.4中的代码显示了这个:

Listing 1.4. The Response class' setRequest method

public void setRequest(Request request) {
    this.request = request;
}

sendStaticResource 方法用来发送一个静态资源,比如HTML文件。Listing 1.5给出了它的实现过程:

Listing 1.5. The Response class' sendStaticResource method

public void sendStaticResource() throws IOException {
    byte[] bytes        = new byte[BUFFER_SIZE];
    FileInputStream fis = null;

    try {
        File file  = new File(HttpServer.WEB_ROOT, request.getUri());
        if (file.exists()) {
            fis    = new FileInputStream(file);
            int ch = fis.read(bytes, 0, BUFFER_SIZE);

            while (ch != -1) {
                output.write(bytes, 0, ch);
                ch = fis.read(bytes, 0, BUFFER_SIZE);
            }
        }
        else {
            // file not found
            String errorMessage = "HTTP/1.1 404 File Not Found/r/n" +
                "Content-Type: text/html/r/n" +
                "Content-Length: 23/r/n" +
                "/r/n" +
                "<h1>File Not Found</h1>";
            output.write(errorMessage.getBytes());
        }
    }
    catch (Exception e) {
        // thrown if cannot instantiate a File object
        System.out.println(e.toString() );
    }
    finally {
        if (fis != null)
            fis.close();
    }
}

sendStaticResource 方法是非常简单的。它首先传递父路径和子路径给File类的构造器,从而对java.io.File类进行了实例化。

File file = new File(HttpServer.WEB_ROOT, request.getUri());

然后它检查文件是否存在。如果存在,sendStaticResource 方法通过传递File对象来构造一个java.io.FileInputStream对象。然后调用FileInputStream 的read方法,将字节流写如到OutputStream输出。注意这种情况下, 静态资源的内容也被作为原始数据被发送给了浏览器。

if (file.exists()) {
    fis    = new FileInputStream(file);
    int ch = fis.read(bytes, 0, BUFFER_SIZE);

    while (ch != -1) {
        output.write(bytes, 0, ch);
        ch = fis.read(bytes, 0, BUFFER_SIZE);
    }
}

如果这个文件不存在,sendStaticResource 方法发送一个错误消息给浏览器。

String errorMessage = "HTTP/1.1 404 File Not Found/r/n" +
    "Content-Type: text/html/r/n" +
    "Content-Length: 23/r/n" +
    "/r/n" +
    "<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());

编译和运行应用程序

为了编译和运行应用,你首先需要解压包含本文应用程序的.zip文件。你解压的目录成为工作目录(working directory),它有三个子目录: src/, classes/, 和 lib/。 要编译应用程序需要在工作目录输入如下语句:

javac -d . src/ex01/pyrmont/*.java

这个-d 选项参数将结果写到当前目录,而不是src/ 目录。

要运行应用程序,在工作目录中输入如下语句:

java ex01.pyrmont.HttpServer

要测试你的应用程序,打开浏览器,在地址栏中输入如下URL:

http://localhost:8080/index.html

你将可以看到浏览器中显示的index.html 页面,如Figure 1所示。

output from the web server
Figure 1. The output from the web server

在控制台(Console),你能看到如下内容:

GET /index.html HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) 
Host: localhost:8080
Connection: Keep-Alive

GET /images/logo.gif HTTP/1.1
Accept: */*
Referer: http://localhost:8080/index.html
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) 
Host: localhost:8080
Connection: Keep-Alive

概要总结

在本文中,你了解了一个简单的WEB服务器的工作机制。本文附带的应用程序源代码只包含三个类,但并不是所有的都有用。尽管如此,它还是能被作为一种很好的学习工具为我们服务。

Translated by Willpower,2003.11.24

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值