基于Jave的Web服务工作机制(7)

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" +
"

1<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. 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服务器的工作机制。本文附带的应用程序源代码只包含三个类,但并不是所有的都有用。尽管如此,它还是能被作为一种很好的学习工具为我们服务。

Published At
Categories with 服务器类
comments powered by Disqus