HttpServer 類
HttpServer類表示一個Web服務(wù)器,且在公共靜態(tài)目錄WEB_ROOT及它的子目錄中能為找到的那些靜態(tài)資源而服務(wù)。WEB_ROOT用以下方式初始化:
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
這段代碼指明了一個包含靜態(tài)資源的webroot目錄,這些資源可用來測試該應(yīng)用。在該目錄中也能找到servlet容器。
要請求一個靜態(tài)資源,在瀏覽器中輸入如下地址或URL:
http://machineName:port/staticResource
machineName 是運行這個應(yīng)用的計算機名或者IP地址。如果你的瀏覽器是在同一臺機器上,可以使用localhost作為機器名。端口是8080。staticResource是請求的文件夾名,它必須位于WEB-ROOT目錄中。
必然,如果你使用同一個計算機來測試應(yīng)用,你想向HttpServer請求發(fā)送一個index.html 文件,那么使用如下URL:
http://localhost:8080/index.html
想要停止服務(wù)器,可以通過發(fā)送一個shutdown命令。該命令是被HttpServer 類中的靜態(tài)SHUTDOWN_COMMAND變量所定義:
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
因此,要停止服務(wù),你可以使用命令:
http://localhost:8080/SHUTDOWN
現(xiàn)在讓我們來看看前面提到的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方法是通過創(chuàng)建一個ServerSocket實例而開始的。然后它進入了一個WHILE循環(huán):
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對象。
新聞熱點
疑難解答
圖片精選