选择显示字体大小

基于java的web服务器工作原理(三)

[b]request 类[/b]

  request 类对应 http 请求。创建这个类的实例,并传给它从 socket 获得的 inputstream 对象,从而捕获与客户端的通信。呼叫 inputstream 对象的 read 方法中的一个就可以得到 http 请求的原始数据。
  request 类有二个 public 方法 parse 与 geturi。parse 方法解析 http 请求的原始数据。它做的事情不多--唯一它使之有效的信息是 http 请求的 uri ,这个通过呼叫私有方法 parseuri 来获得。parseuri 方法把 uri 作为一个变量。调用 geturi 方法可以得到 http 请求的 uri 。
  要明白 parse 与 parseuri 的工作原理,你需要知道 http 请求的结构,由 rfc2616 定义。
  一个 http 请求包括三个部分:
request line
headers
message body
  现在,我们只需要关注 http 请求的第一部分--请求行。请求行以方法记号开始,接着是请求的 uri 与协议版本,以回车换行符结束。请求行的元素之间以空格分开。例如,一个用 get 方法的 index.html 文件的请求行如下:
get /index.html http/1.1
  parse 方法从 socket 的 inputstream 传递给 request 对象中读取字节流,把这个字节数组存在缓冲里。然后,它把 buffer 字节数组里的字节放入叫做 request 的 stringbuffer 对象中,再把 stringbuffer 替换成 string 传递给 parseuri 方法。
  parse 方法的代码如列表 1.2
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 。列表 1.3 展示了 parseuri 方法的代码。
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 对象通过传递从 socket 获得的 outputstream 对象到 httpserver 类的 await 方法而创建。
  response 类有二个公共方法 setrequest 与 setstaticresource 。setrequest 用来传递 request 对象到 response 对象。它比较简单,代码如列表 1.4 所示:
listing 1.4. the response class' setrequest method

public void setrequest(request request) {
    this.request = request;
}

  sendstaticresource 方法用来发送静态的资源,例如 html 文件。它的实现如列表 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 = &quot;http/1.1 404 file not found\r\n&quot; +
                &quot;content-type: text/html\r\n&quot; +
                &quot;content-length: 23\r\n&quot; +
                &quot;\r\n&quot; +
                &quot;<h1>file not found</h1>&quot;;
            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 对象 output 。就这样,静态资源的内容作为原始数据被发送到浏览器。
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 = &quot;http/1.1 404 file not found\r\n&quot; +
    &quot;content-type: text/html\r\n&quot; +
    &quot;content-length: 23\r\n&quot; +
    &quot;\r\n&quot; +
    &quot;<h1>file not found</h1>&quot;;
output.write(errormessage.getbytes());


  编译与运行应用程序

  要编辑与运行本文的应用,首先你需要解压源码 zip 文件。直接解压出来的目录被称为工作目录,它有三个子目录:src/,classes/,lib/。要编译应用,从工作目录输入如下命令:
javac -d . src/ex01/pyrmont/*.java
  -d 选项把结果写到当前目录,而不是 src/ 目录。
  要运行应用,在当前工作目录输入如下命令:
java ex01.pyrmont.httpserver
  测试这个应用,打开你的浏览器,在地址栏输入如下地址:
http://localhost:8080/index.html
  你将在你的浏览器看到 index.html 显示出来,如图1所示。

图1:web 服务器的输出显示

在控制台,你看到如下的内容:
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 服务器的工作原理。本文相关的应用只包括了三个类,功能是不全面的。然而,它仍不失为一个好的学习工具。


matrix开源技术经onjava授权翻译并发布.
如果你对此文章有任何看法或建议,请到matrix论坛发表您的意见.
注明: 如果对matrix的翻译文章系列感兴趣,请点击oreilly和javaworld文章翻译计划查看详细情况
您也可以点击-fajaven查看翻译作者的详细信息.


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons