手写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();
}
}
}