手寫Web Server 和Browser,展示靜態頁面。
1)自己寫一個WebServer:
啓動此WebServer 類(Web服務器核心代碼)後,瀏覽器中輸入http://localhost:9999,Server 會接收到瀏覽器發來的請求頭,並返回頁面數據,瀏覽器即可訪問到index.html。
VS: 啓動Tomcat 服務器(C:\Program Files\apache-tomcat-8.5.24\bin\startup.bat),將index.html 放在C:\Program Files\apache-tomcat-8.5.24\webapps\ROOT,
瀏覽器即可訪問 http://localhost:8080/index.html
URL = 協議(http) + 主機(服務器(www, mail etc)+域名) + 端口(80 可省略)
Web應用程序 指供瀏覽器訪問的程序,也簡稱爲 web應用。
它由多個靜態web資源和動態資源組成:java, jar包, 配置文件, jsp, html 等。
用一個目錄組織這些文件,此目錄即web應用所在目錄。
web應用所在目錄 交給 web服務器管理,此過程叫 虛擬目錄的映射,以下是三種方法:
(1)在server.xml 裏Host元素內配置Context:
<Context path="/itrocks" docBase="E:\IDEA Projects\Itrocks_03_StaticWeb\src\webapp"/>
重啓Tomcat 纔可生效,所以不推薦這種方法。
(2)在C:\Program Files\apache-tomcat-8.5.24\conf\Catalina\localhost 新建itrocks.xml, 內容:
<Context docBase="E:\IDEA Projects\Itrocks_03_StaticWeb\src\webapp"/>
此法不需要重啓。
(3)將文件夾放在 C:\Program Files\apache-tomcat-8.5.24\webapps 即可自動映射。
public class WebServer {
public static void main(String[] args) {
System.out.println("Listening to request: ");
String path = "E:\\IDEA Projects\\Itrocks_02_TCP_IP\\src\\webapp\\index.html";
try (ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(path)) {
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println(len);
System.out.println(new String(bytes, 0, len));
int read = fis.read(bytes);
os.write(bytes, 0, read);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2)自己寫一個Browser:Tomcat 啓動後,此類可向瀏覽器發送請求,得到resource.
Tomcat 的日誌localhost_access_log.2018-03-18.txt會有訪問記錄:
127.0.0.1 - - [18/Mar/2018:20:16:21 +0800] "GET / HTTP/1.1" 200 202
public class Brower {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080)) {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("GET / HTTP/1.1");
out.println("ACCEPT */*");
out.println("Host: localhost:8080");
out.println("Connection: keep-alive");
out.println("");
out.println("");
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = in.read(bytes);
String str = new String(bytes, 0, read);
System.out.println(str);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}