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

在下面的段落中,让我们来看看这三个类吧。

HttpServer 类

HttpServer类表示一个web服务器,且在公共静态目录WEB_ROOT及它的子目录中能为找到的那些静态资源而服务。WEB_ROOT用以下方式初始化:

public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";

这段代码指明了一个包含静态资源的webroot目录,这些资源可用来测试该应用。在该目录中也能找到servlet容器。

要请求一个静态资源,在浏览器中输入如下地址或URL:

http://machineName:port/staticResource
machineName 是运行这个应用的计算机名或者IP地址。如果你的浏览器是在同一台机器上,可以使用localhost作为机器名。端口是8080。staticResource是请求的文件夹名,它必须位于WEB-ROOT目录中。

必然,如果你使用同一个计算机来测试应用,你想向HttpServer请求发送一个index.html 文件,那么使用如下URL:

http://localhost:8080/index.html

想要停止服务器,可以通过发送一个shutdown命令。该命令是被HttpServer 类中的静态SHUTDOWN_COMMAND变量所定义:

private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
因此,要停止服务,你可以使用命令:

http://localhost:8080/SHUTDOWN
现在让我们来看看前面提到的await方法。下面一个程序清单给出了解释。

Listing 1.1. The HttpServer class' await method

public void await() {
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}

// Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();

// create Request object and parse
Request request = new Request(input);
request.parse();

// create Response object
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();

// Close the socket
socket.close();

//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
continue;
}
}
}

await方法是通过创建一个ServerSocket实例而开始的。然后它进入了一个WHILE循环:

serverSocket = new ServerSocket(
port, 1, InetAddress.getByName("127.0.0.1"));

...

// Loop waiting for a request
while (!shutdown) {
...
}

socket = serverSocket.accept();
在收到一个请求后,await方法从accept方法返回的socket实例中获得java.io.InputStream 和java.io.OutputStream对象。

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