//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) { ... }
在 while 循環中的代碼,運行到 ServerSocket 的 accept 方法即停止。這個方法只有在 8080 端口接收到 HTTP 請求才返回: socket = serverSocket.accept(); 收到請求后,await 方法從 accept 方法返回的 Socket 實例中等到 java.io.InputStream 與 java.io.OutputStream: input = socket.getInputStream(); output = socket.getOutputStream(); 然后 await 方法創建一個 Request 對象,呼叫它的 parse 方法來解析這個原始的 HTTP 請求: // create Request object and parse Request request = new Request(input); request.parse(); 下一步,await 方法創建一個 Response 對象并把 Request 對象設置給它,呼叫它的 sendStaticResource 方法: // create Response object Response response = new Response(output); response.setRequest(request); response.sendStaticResource(); 最后,await 方法關閉 Socket ,呼叫 Request 的 getUri 方法來檢查 HTTP 請求的地址是否是一個停止命令。如果是,則 shutdown 變量被設置為 true ,程序退出 while 循環: // Close the socket socket.close(); //check if the previous URI is a shutdown command shutdown = request.getUri().equals(SHUTDOWN_COMMAND);